ctrlplusb / react-async-component

Resolve components asynchronously, with support for code splitting and advanced server side rendering use cases.
MIT License
1.45k stars 62 forks source link

How to call async component's internal function #55

Closed FallOutChonny closed 6 years ago

FallOutChonny commented 6 years ago

I'm having a little problem. Say I have an async component that is encapsulated with react-async-component, like this:

const AsyncComponent = asyncComponent({
  resolve: () => new Promise(resolve =>
    require.ensure([], require => {
      resolve(require('draft-js'))
    }
  )
})

then call its internal functions by refs

<AsyncComponent ref={c => this.editor = c} />

this.editor.focus();

but will get Uncaught TypeError: _this.editor.focus is not a function error, and I use console.log(this.editor) see it's a async component and has not focus function so that I can't access it.

I spent a lot of time but still have no idea how to fix it, does anyone can help ? thanks 😄

FallOutChonny commented 6 years ago

Ok, finally I found the approach solved it,

in main component, pass a onRef prop to AsyncComponent

<AsyncComponent
  onRef={c => this.editor = c}
/>

in Async Component, return this

componentDidMount() {
  this.props.onRef(this);
}

then you can do like so from main component.

this.editor.clear();
this.editor.focus();