5

原始问题: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" />
   }
}
4

1 回答 1

3

您可以使用提升静态

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

const enhance = compose(...some)

const Component = hoistStatics(enhance)(BaseComponent)

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

你可以在测试中找到一个真实的例子。

于 2016-09-12T08:45:25.040 回答