【问题标题】:How to access component with ref when it wrapped by withRouter in NextJS?NextJS 中的 withRouter 包裹组件时如何使用 ref 访问组件?
【发布时间】: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 组件>

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    我认为以下之一应该可以工作

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

    第二个选项

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

    【讨论】:

      猜你喜欢
      • 2018-10-09
      • 1970-01-01
      • 2022-10-20
      • 2022-11-17
      • 1970-01-01
      • 2020-06-12
      • 2018-01-03
      • 2022-12-10
      • 2020-02-24
      相关资源
      最近更新 更多