【问题标题】:losing functions when using recompose component as ref使用 recompose 组件作为 ref 时丢失功能
【发布时间】:2018-10-13 13:53:53
【问题描述】:

我有这个简单的组件

class App extends React.Component {
  a = () => null
  b = () => null
  c = () => null

  render() {
    return (<div>hey123</div>)
  }
}

这是我的第二个组件,参考第一个组件

class BApp extends React.Component {
  setComponentRef = ref => {
    console.log('ref', ref)
    this.playerComponentRef = ref
  }
  render() {
    return (
      <div>
        <App ref={this.setComponentRef} />
      </div>)
  }  
}

在这种情况下,在 console.log 中,我将收到所有 App 组件的功能(a、b、c) 但如果我在App 组件上使用Recompose.withState,我将不再收到它们。看这里的例子 https://codepen.io/anon/pen/qYjpoE?editors=1111

查看工作方式开关

<ModifyedApp ref={this.setComponentRef} />

<App ref={this.setComponentRef} />

我在这里错过了什么?为什么使用 Recompose HOC 会删除 App 类组件内部函数?

谢谢。

【问题讨论】:

    标签: javascript reactjs recompose


    【解决方案1】:

    您可以将函数providerRef 传递给您的组件,然后向它提供 App 实例

    class BApp extends React.Component {
      setComponentRef = ref => {
        console.log('ref', ref)
        this.playerComponentRef = ref
      }
      render() {
        return (
          <div>
            <App providerRef={this.setComponentRef} />
          </div>)
      }  
    }
    
    
    class App extends React.Component {
      a = () => null
      b = () => null
      c = () => null
      componentDidMount() {
         this.props.providerRef(this);
      }
      render() {
        return (<div>hey123</div>)
      }
    }
    

    在 Recompose 的情况下,它是一个 HOC,因此 ref 将应用于 HOC 而不是内部组件,一些库提供了一个 withRef 挂钩来使用 this.playerComponentRef.getWrappedInstance() 访问 innerComponent ref,但是我不确定关于它的可用性在recompose

    【讨论】:

      【解决方案2】:

      HOC 将在子组件之外创建一个新组件。因此,如果您在 HOC 中包装子组件并尝试接收包装组件的 ref,您将获得 HOCs ref

      这里有一个解决方法 - 只需将 ref 从父组件传递给 hoc 中的子组件 - 只需代理 ref。

      【讨论】:

      • 感谢您的回复,“将 ref 从父组件传递给 hoc 中的子组件”您能举个例子吗?
      猜你喜欢
      • 2018-03-16
      • 2017-12-31
      • 2019-12-11
      • 1970-01-01
      • 2021-08-07
      • 2022-08-06
      • 1970-01-01
      • 2018-06-29
      • 1970-01-01
      相关资源
      最近更新 更多