在NextJS中使用withRouter包装时,如何使用ref访问组件?

reactjs React.js

2020-03-27

我有一个React组件,我这样导出它:

class Child extends Component {
  getStatus() {
    return 'I am child!';
  }
  render() {
    return (<div>Child</div>);
  }
}

export default withRouter(Child)

我还有另一个需要这样的“ 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用Router>包装时,如何访问子引用组件

第3810篇《在NextJS中使用withRouter包装时,如何使用ref访问组件?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
飞云 2020.03.27

我认为以下其中一项应该有效

export default withRouter(Child, { withRef: true })

第二选择

 this.childComponent = React.createRef();
....
<Child wrappedComponentRef={c => (this.childComponent  = c)} />

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android