【问题标题】:useRef for showing the count of characters inside a textareauseRef 用于显示文本区域内的字符数
【发布时间】: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&lt; textarea&gt;{props.value}&lt;/textarea&gt;
  • 你能回答一下吗?
  • 它适用于您的示例,但我无法将其转换为仅一个组件,在您的示例中,您是从应用程序发送道具。是否可以使其成为组件的内部功能?我试图修改你的代码但没有成功

标签: javascript reactjs typescript react-hooks use-ref


【解决方案1】:

将 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} />

【讨论】:

    【解决方案2】:

    你可以这样做

    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]);
    

    【讨论】:

      猜你喜欢
      • 2020-03-21
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多