【发布时间】:2019-09-18 00:57:29
【问题描述】:
我有一个 React 组件,我像这样导出它:
class Child extends Component {
getStatus() {
return 'I am child!';
}
render() {
return (<div>Child</div>);
}
}
export default withRouter(Child)
我还有另一个类需要像这样的“子”组件的引用:
class Parent extends Component {
constructor(props) {
super(props);
this.childRef = createRef();
}
handleLogChildStatus = () => {
if (typeof this.childRef.current.getStatus === 'function') {
console.log(this.childRef.current.getStatus());
} else {
console.log(' Can not access to child component via ref! ');
}
}
render() {
return (
<div>
<Child ref={this.childRef} />
<div onClick={this.handleLogChildStatus}>Log child status</div>
</div>
);
}
}
此示例显示我无法访问子组件 ref,因为它由 withRouter HOC 包装。
我的问题是当它被 nextjs withRouter 包裹时,我如何访问子 ref 组件>
【问题讨论】: