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

2024-03-13

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

下面是该方法的一个工作示例:https://codesandbox.io/s/rwj7z7o7oo https://codesandbox.io/s/rwj7z7o7oo


原帖:

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

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} />
    );
}

是否有另一种方法可以让我在子级和父级中使用引用?


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

此外,您还没有从子组件返回任何内容。

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} />;
};

工作演示 https://codesandbox.io/s/5kw376nx1p

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React - 在组件中使用 ref 并将其传递给 props 中的父级 的相关文章

随机推荐