【问题标题】:React trying to call child (useRef) function in a functional componentReact 尝试在功能组件中调用子 (useRef) 函数
【发布时间】:2020-02-08 15:38:35
【问题描述】:

我有一个子组件正在生成并显示一个随机数。
我正试图从父母那里控制它。
但参考电流为空。

如何在功能组件中从父级调用子函数
https://codesandbox.io/s/busy-joliot-85yom

function App() {
  const child = useRef();
  const generate = () => child.current.generate();

  return (
    <div className="App">
    <br />
      <Child ref={child}></Child><br />
      <button onClick={generate}>regenerate from parent (Not working)</button>
    </div>
  );
}

function Child(props){
  const [number, setNumber] = useState(0);
  const generate = () => setNumber(Math.round(Math.random() * 10));
  return <div>{number} <br /> <button onClick={generate}>regenerate from child</button></div>;
}

谢谢

【问题讨论】:

  • 为什么不将() =&gt; setNumber(Math.round(Math.random() * 10)); 传递给父子生成?
  • @HMR 你能在这里展示这个例子吗:codesandbox.io/s/busy-joliot-85yom ?谢谢
  • 当然,here 就是一个例子。
  • 查看控制台:警告:函数组件不能被赋予引用。尝试访问此 ref 将失败。你的意思是使用 React.forwardRef() 吗?

标签: reactjs react-functional-component


【解决方案1】:

你不能在函数组件中使用 ref 属性,但是你可以自己处理任何 ref 对象,只是不要称它为“ref”,react 不喜欢它。 检查我的example

【讨论】:

    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 2021-08-16
    • 2021-07-15
    • 1970-01-01
    • 2023-03-27
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多