【发布时间】:2022-01-24 00:21:44
【问题描述】:
具有以下组件:
import React from 'react';
export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
maxLength?: number;
id: string;
}
export const Textarea = React.forwardRef(
(
{ id = 'my-id', maxLength = 200, ...props }: TexareaProps,
ref: React.ForwardedRef<HTMLTextAreaElement>
) => {
return (
<div className='relative flex flex-col'>
<textarea id={id} maxLength={maxLength} {...props}></textarea>
</div>
);
}
);
export default Textarea;
它返回一个文本区域,用户可以在其中写入最多 200 个字符。我的目标是在某处显示当前的书面字符数,因此为了做到这一点,组件必须使用useRef 挂钩来访问文本区域。
在普通的 JS 中是这样的:
const toCheck = document.getElementById('my-id');
console.log(toCheck.value.length); // this will log the current count of written chars
但是用 useRef 怎么办呢?
【问题讨论】:
-
传入
value属性(在大多数情况下将通过状态使用),然后使用value.length。并且不要忘记将value作为孩子设置为textarea:< textarea>{props.value}</textarea> -
你能回答一下吗?
-
它适用于您的示例,但我无法将其转换为仅一个组件,在您的示例中,您是从应用程序发送道具。是否可以使其成为组件的内部功能?我试图修改你的代码但没有成功
标签: javascript reactjs typescript react-hooks use-ref