这里使用react 封装的组件 调用自动聚焦到 文本最后 .
autofocus 自动聚焦
捕获input dom
使用 textareaRef.current?.setSelectionRange(-1, -1); (-1, -1)表示聚焦到文字最后. (0, 0) 表示 聚焦到开头位置.

import classNames from 'classnames';
import styles from './index.module.scss';
import { useRef, useEffect } from 'react';
// 1,定义props类型
interface textareaProps
extends React.DetailedHTMLProps<
React.TextareaHTMLAttributes<HTMLTextAreaElement>,
HTMLTextAreaElement
> {
value: string;
}
export default function Textarea(props: textareaProps) {
//2.1声明ref
const textareaRef = useRef<HTMLTextAreaElement>(null);
//2,实现最大的长度限制 默认值是100
const {
maxLength = 100,
className,
value,
autoFocus = true,
...restProps
} = props;
//2.3 生命周期挂载后触发 光标选中
//https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLInputElement/setSelectionRange 控制光标出现的位置光标在
useEffect(() => {
textareaRef.current?.setSelectionRange(-1, -1);
}, []);
return (
<div className={styles.root}>
{/* 文本输入框 */}
<textarea
//2.2 绑定ref
ref={textareaRef}
className={classNames('textarea', className)}
{...restProps}
maxLength={maxLength}
//4, 统计当前字数
value={value}
autoFocus={autoFocus}
/>
{/* 当前字数/最大允许字数 */}
<div className="count">
{value.length}/{maxLength}
</div>
</div>
);
}
本文介绍了如何在React组件中利用textareaRef和setSelectionRange方法,实现文本输入框的自动聚焦,并使光标定位在文字结尾。通过设置setSelectionRange的参数为(-1, -1),可以达到此效果,而(0, 0)则会使光标位于开头。"
132857324,19694729,保持C++与QT库函数名不变的技巧,"['C/C++', 'QT框架', '编程实践', '跨平台开发', '函数导出']

2488

被折叠的 条评论
为什么被折叠?



