更新:我的问题实际上是由于拼写错误 - 如果您想在子组件和父组件中使用子元素 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} />
);
}
是否有另一种方法可以让我在 Child 和 Parent 中使用 ref?