[英]useRef for showing the count of characters inside a textarea
具有以下组件:
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
挂钩来访问 textarea。
在普通的 JS 中,它会是这样的:
const toCheck = document.getElementById('my-id');
console.log(toCheck.value.length); // this will log the current count of written chars
但是如何使用 useRef 来完成呢?
将 ref 传递给 textarea
<textarea ref={ref} id={id} maxLength={maxLength}{...props}></textarea>
你可以像这样使用组件Textarea
const textAreaRef = useRef<HTMLTextAreaElement>()
console.log(textAreaRef.current?.value.length)
return <Textarea ref={textAreaRef} />
你可以这样做
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 {...props} ref={ref} id={id} maxLength={maxLength}></textarea>
</div>
);
}
);
export default Textarea;
然后在父级中,您可以显示字符数
const textAreaRef = useRef();
useEffect(() => {
if (textAreaRef.current) {
console.log(textAreaRef.current.value.length);
}
}, [textAreaRef]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.