我有两个 React 组件,Parent 和 Child。两者都必须是函数组件。我正在尝试改变父级的子级状态。我相信最好的方法是使用 refs,但我还没能让它发挥作用。
我尝试在父级中创建引用并将其传递给子级,但这会导致错误。我考虑过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 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use 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>;
关于javascript - 当父级和子级是函数组件时,React refs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57478873/