reactjs - React 尝试在功能组件中调用子 (useRef) 函数
问题描述
我有一个子组件正在生成和显示一个随机数。
我试图从父母那里控制它。
但参考电流为空。
如何从功能组件中的父级调用子函数
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>;
}
谢谢
解决方案
你不能在功能组件中使用 ref 属性,但是你可以自己处理任何 ref 对象,只是不要称它为“ref”,react 不喜欢它。检查我的例子
推荐阅读
- python-3.x - VS-Code 和 Python - 入门教程中的问题
- php - 将菜单标题从 h2 更改为 h3 (woocommerce / wordpress)
- git - 如何自动为每个远程查找默认分支?
- reporting-services - 自动 SSRS 报告部署
- python-3.x - 无法使用模块 python_terraform 通过 python 包装器将 variables.tfvars 文件中的值替换为输入变量
- port - 如何更改已发布 Blazor Server 项目的端口?
- angular - 如何在 Angular 11 测试中检查 scss 变量
- javascript - 如何在JS中的元素上获取:悬停样式
- java - 对于这种情况,我可以避免转换为 T 吗?
- javascript - 如何使用javascript仅记录匹配的条件?