next.js动态引入组件的时候,ref不能用的问题

啊哈,这是个令人头秃的问题 (:з」∠)

问题:

next.js动态引入组件的时候,ref不能用,不生效。打印出来都是undefined

原因:

找到开发者回复:

There’s a new API coming in future React that allows to pass off ref.


Expecting this to be one of the cases for the new createRef API

这、不能吧 (:з」∠) 但还是有能曲线救国的方法,就是自己再封装一层。

解决:

例子

class Graphin extends React.Component {
  private refCom: any;

  constructor(props) {
    super(props);
    this.state = {
      DynamicComponent: null,
    };
    this.refCom = React.createRef();
  }

  componentDidMount() {
    import('@antv/graphin').then((val) => this.setState({ DynamicComponent: val.default }));
  }

  render() {
    const { DynamicComponent } = this.state;
    return DynamicComponent && <DynamicComponent ref={this.refCom} {...this.props} />;
  }
}

使用

const graphRef = useRef(null);

<Graphin
	style=
  ref={graphRef}
  data=
/>

参考资料:

React ref doesn’t work with dynamically imported components #2842

ref doesn’t work with dynamically imported components #4957