当 children 是功能组件时如何获取它的引用
How to get the ref of a children when its a functional component
我正在尝试创建一个 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>
);
}
const Example = React.forwardRef((props, ref) => <div ref={ref}>example</div>);
我正在尝试创建一个 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>
);
}
const Example = React.forwardRef((props, ref) => <div ref={ref}>example</div>);