美文网首页
【react】forwardRef报错

【react】forwardRef报错

作者: 西叶web | 来源:发表于2023-08-11 18:40 被阅读0次

    报错

    [object Object]: ref is not a prop. Trying to access it will result in undefined being returned. If you need to access the same value within the child component, you should pass it as a different prop.

    解决

    你不该在forwordRef的组件内一开始就打印ref

    示例

    import { useRef ,forwardRef} from 'react';
    const MyInput = forwardRef(function MyInput(props, ref) {
      // console.log('props, ref: ', props, ref); // 直接打印就会报错
      const { label, ...otherProps } = props;
      return (
        <label>
          {label}
          <input {...otherProps} ref={ref} />
        </label>
      );
    });
    
    export default function Form() {
      const ref = useRef(null);
    
      function handleClick() {
        ref.current.focus();
      }
    
      return (
        <form>
          <MyInput label="Enter your name:" ref={ref} />
          <button type="button" onClick={handleClick}>
            Edit
          </button>
        </form>
      );
    }
    

    相关文章

      网友评论

          本文标题:【react】forwardRef报错

          本文链接:https://www.haomeiwen.com/subject/xhvtmdtx.html