javascript - 当 parent 和 child 是函数组件时 React refs
问题描述
我有两个 React 组件,Parent 和 Child。两者都必须是功能组件。我正在尝试从父级更改子级的状态。我相信最好的方法是使用 refs,但我无法让它工作。
我尝试在 Parent 中创建一个 ref 并将其传递给 child,但这会导致错误。我考虑过 forwardRef() 但我不确定它是否会起作用。
const Parent = () => {
const ref = React.useRef();
const closeChild = () => {
ref.current.setOpen(false);
};
return (
<div>
<Child ref={ref} onClick={closeChild} />
</div>
);
};
const Child = () => {
const [open, setOpen] = useState(false);
return (
<div>
{open ? <p>open</p> : <p>closed</p>}
</div>
);
};
现在的代码会产生以下错误消息:
react-dom.development.js:506 警告:不能给函数组件提供参考。尝试访问此 ref 将失败。你的意思是使用 React.forwardRef() 吗?
解决方案
只有有状态的 React 组件才能自动公开 ref。如果使用功能组件,我认为您需要对子组件使用 forwardRef:例如
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
推荐阅读
- azure-sql-database - Power BI 与 DB 的最大连接:( 我们可以使用单个 Sql.Database 调用填充多个表吗?
- algorithm - 从另一个 bst 的元素构造二叉搜索树的算法
- python - 我的 for 循环返回我的 python 代码中所有迭代的最后一个值
- javascript - 使用 javascript 添加带有数据库值的选择字段
- swagger - 带有uaa服务的Jhipster微服务架构,swagger post方法,access_denied Invalid CSRF Token
- javascript - 从 html 字符串名称值对中获取属性
- java - 为什么尝试获取 Clip 会引发异常?
- java - 如何从 Handler 更改 Activity?
- go - 我如何知道拉取了哪个版本的依赖项?
- vb.net - 从 AnyCPU 更改为 x86 会导致 System.BadImageFormatException 错误