当子组件是一个功能组件时,如何获取子组件的ref



我试图创建一个HOC来获得任何组件的ref

当我通过正常的jsx,工作良好。但是当我传入一个功能组件时,它不起作用:

class GetRef extends React.Component {
state = {};
constructor(props) {
super(props);
this.renderChildren = this.renderChildren.bind(this);
}
componentDidMount() {
this.props.setRef(this.ref);
}
renderChildren() {
const childElement = React.Children.only(this.props.children);
return React.cloneElement(childElement, { ref: (el) => (this.ref = el) });
}
render() {
return <>{this.renderChildren()}</>;
}
}
const RefRegister = ({ children }) => {
const [ref, setRef] = useState();
console.log({ ref });
return <GetRef setRef={setRef}>{React.Children.only(children)}</GetRef>;
};
const Example = () => <div>example</div>;
export default function App() {
return (
<div className="App">
<RefRegister>
{/* <div>example</div> */} Works well in this case
<Example /> // Throws an error passing a component :(
</RefRegister>
</div>
);
}

演示

use React.forwardRef:

const Example = React.forwardRef((props, ref) => <div ref={ref}>example</div>);

Demo - https://codesandbox.io/s/practical-proskuriakova-ywdj6

最新更新