【发布时间】: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>;
}
谢谢
【问题讨论】:
-
为什么不将
() => setNumber(Math.round(Math.random() * 10));传递给父子生成? -
@HMR 你能在这里展示这个例子吗:codesandbox.io/s/busy-joliot-85yom ?谢谢
-
当然,here 就是一个例子。
-
查看控制台:警告:函数组件不能被赋予引用。尝试访问此 ref 将失败。你的意思是使用 React.forwardRef() 吗?
标签: reactjs react-functional-component