如何访问 BaseComponent 的 ref 或任何级别的组件?

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

原问题:https://github.com/acdlite/recompose/issues/232

如何访问 BaseComponent 或任何级别的组件的引用?

代码:

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" />
   }
}

您可以使用 hoistStatic.

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

const enhance = compose(...some)

const Component = hoistStatics(enhance)(BaseComponent)

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

你可以找到一个真实的例子in the test