简体   繁体   English

useRef 用于显示文本区域内的字符数

[英]useRef for showing the count of characters inside a textarea

Having the following component:具有以下组件:

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;

It returns a textarea where a user can write up to 200 characters.它返回一个文本区域,用户可以在其中写入最多 200 个字符。 My aim is to show somewhere the current count of written characters, so in order to do that the component must use useRef hook to access the textarea.我的目标是在某处显示当前的书面字符数,因此为了做到这一点,组件必须使用useRef挂钩来访问 textarea。

In plain JS it would be like:在普通的 JS 中,它会是这样的:

const toCheck = document.getElementById('my-id');
console.log(toCheck.value.length); // this will log the current count of written chars

But how can it be done with useRef?但是如何使用 useRef 来完成呢?

pass ref to textarea将 ref 传递给 textarea

<textarea ref={ref} id={id} maxLength={maxLength}{...props}></textarea>

and you can use component Textarea like this你可以像这样使用组件Textarea

const textAreaRef = useRef<HTMLTextAreaElement>()

console.log(textAreaRef.current?.value.length)

return <Textarea ref={textAreaRef} />

You can do it like this你可以这样做

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;

and then in the parent, you can show the number of character然后在父级中,您可以显示字符数

const textAreaRef = useRef();

useEffect(() => {
  if (textAreaRef.current) {
    console.log(textAreaRef.current.value.length);
  }
}, [textAreaRef]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM