【问题标题】:How can I access the ref of the BaseComponent or any level of the components?如何访问 BaseComponent 或任何级别的组件的引用?
【发布时间】:2023-04-02 05:30:01
【问题描述】:

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

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

代码:

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

【问题讨论】:

    标签: reactjs recompose


    【解决方案1】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2010-12-11
      • 2014-08-11
      • 2018-04-09
      • 2016-10-05
      • 1970-01-01
      相关资源
      最近更新 更多