Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the ref of the BaseComponent or any level of the components?

Original question: https://github.com/acdlite/recompose/issues/232

How can I access the ref of the BaseComponent or any level of the components?

Code:

class BaseComponent {
    doSth(){...}
}
const Component compose(...some)(BaseComponent);

class App {
    componentDidMount() {
        // undefined(doSth) is not a function
        this.refs.component.doSth();
    }
    render() {
        <Component ref="component" />
   }
}
like image 501
Fernando Montoya Avatar asked Oct 19 '22 02:10

Fernando Montoya


1 Answers

You can use hoistStatic.

class BaseComponent {
  doSth(){...}
}

const enhance = compose(...some)

const Component = hoistStatics(enhance)(BaseComponent)

class App {
  componentDidMount() {
    this.refs.component.doSth()
  }
  render() {
    <Component ref="component" />
  }
}

You can find a real example in the test.

like image 65
wuct Avatar answered Oct 21 '22 06:10

wuct