【问题标题】:React - useRef with TypeScript and functional componentReact - useRef 与 TypeScript 和功能组件
【发布时间】:2020-06-18 15:25:29
【问题描述】:


我试图从父组件调用子组件方法,并且试图使用 useRef。未来,SayHi 方法将在子组件中更新钩子状态。不幸的是,我有一些我无法处理的错误。

行:ref.current.SayHi();

'ForwardRefExoticComponent void; }>>'。

行:

类型'RefObject void; }>>>' 不能分配给类型 '((instance: { SayHi: () => void; } | null) => void) | RefObject void; }> |空 |不明确的'。 类型 'RefObject 无效; }>>>' 不能分配给类型 'RefObject void; }>'。 'ForwardRefExoticComponent void; }>>' 但在 '{ SayHi: () => void; 类型中是必需的}'。


完整的 test.tsx 文件:

import React, { useRef, forwardRef, useImperativeHandle, Ref } from 'react'

const Parent = () => {
    const ref = useRef<typeof Child>(null);
    const onButtonClick = () => {
      if (ref.current) {
        ref.current.SayHi();
      }
    };
    return (
      <div>
        <Child name="Adam" ref={ref}/>
        <button onClick={onButtonClick}>Log console</button>
      </div>
    );
  }

const Child = forwardRef((props: {name: string}, ref: Ref<{SayHi: () => void}>)=> {
  const {name} = props;
  useImperativeHandle(ref, () => ({ SayHi }));

  function SayHi() { console.log("Hello " + name); }

  return <div>{name}</div>;
});

我在这个话题上深深地寻求帮助。

【问题讨论】:

    标签: reactjs typescript ref tsx react-functional-component


    【解决方案1】:

    您需要在别处提取 ref 类型:

    interface RefObject {
      SayHi: () => void
    }
    

    然后在两个地方都引用它

    const Child = forwardRef((props: {name: string}, ref: Ref<RefObject>)=> {
      const {name} = props;  
      useImperativeHandle(ref, () => ({ SayHi }));
      function SayHi() { console.log("Hello " + name); }
    
      return <div>{name}</div>;
    });
    
    const Parent = () => {
        const ref = useRef<RefObject>(null);
        const onButtonClick = () => {
          if (ref.current) {
            ref.current.SayHi();
          }
        };
        return (
          <div>
            <Child name="Adam" ref={ref}/>
            <button onClick={onButtonClick}>Log console</button>
          </div>
        );
    }
    

    【讨论】:

    • 非常感谢! :)
    【解决方案2】:

    只需将 ref 的声明替换为 const ref = useRef&lt;{ SayHi: () =&gt; void }&gt;(null);

    【讨论】:

      猜你喜欢
      • 2019-11-03
      • 2020-12-20
      • 1970-01-01
      • 2022-01-01
      • 2020-12-30
      • 2016-04-17
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多