React-在组件中使用ref并将其传递给props的parent

时间:2018-11-22 05:03:36

标签: reactjs react-hooks

更新:我的问题实际上是由于拼写错误-如果您想在子组件和父组件中都使用子元素ref,则一般方法可以正常工作。

这是一种可行的方法的工作示例: https://codesandbox.io/s/rwj7z7o7oo


原始帖子:

我正在尝试将ref转发给父组件,同时还使该ref可访问子级(这是一个类)中的函数。目前,我可以成功地将ref传递给父级,但是该子级中的ref不再可用。

class Child extends React.Component {
    // Unable to access the forwarded ref here:
    componentDidMount() {
        console.log(this.props.forwardedRef); // null
    }

    render() {
        return <input type="text" ref={this.props.forwardedRef} />
    }
}

// Parent is able to access the ref:
const Parent = () => {
    const childRef = useRef(null);

    function handleClick() {
        console.log(childRef.current); // correctly ref's the input el
    }

    return (
        <Child forwardedRef={childRef} onClick={handleClick} />
    );
}

还有其他方法可以让我在“孩子”和“父母”中使用引用吗?

1 个答案:

答案 0 :(得分:2)

useRef返回类似于实例变量类的值。在您的情况下,即使您设置了ref,也不会导致组件呈现,因此child的componentDidUpdate无法运行。

您还没有从Child组件返回任何信息。

class Child extends React.Component {
  // Unable to access the forwarded ref here:
  componentDidUpdate(prevProps) {
    console.log(this.props.forwardedRef); // null
    console.log(prevProps.forwardedRef); // null
  }

  render() {
    return (
      <React.Fragment>
        <input type="text" ref={this.props.forwardedRef} />
        <div>{this.props.count}</div>
        <input type="button" onClick={this.props.onClick} value={"Click"} />
      </React.Fragment>
    );
  }
}

// Parent is able to access the ref:
const Parent = () => {
  const childRef = useRef(null);
  const [count, setCount] = useState(0);

  function handleClick() {
    console.log(childRef.current); // correctly ref's the input el
    setCount(count => count + 1);
  }

  return <Child forwardedRef={childRef} count={count} onClick={handleClick} />;
};

Working demo