首页 > 解决方案 > 当 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() 吗?

标签: javascriptreactjs

解决方案


只有有状态的 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>;

推荐阅读