javascript - 使用重组组件作为 ref 时丢失功能

标签 javascript reactjs recompose

我有这个简单的组件

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 类组件内部函数?

谢谢。

最佳答案

您可以将函数 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 钩子(Hook)来使用 this 访问 innerComponent ref .playerComponentRef.getWrappedInstance(),但是我不确定它在 recompose 中的可用性。

关于javascript - 使用重组组件作为 ref 时丢失功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151848/

相关文章:

javascript - 解析 XML namespace ?

javascript - 在谷歌浏览器 32 中打开 angularjs 应用程序显示空白页面

javascript - 如何将 Javascript 中的转义字符转换为 .txt 文件?

reactjs - Semantic-ui-react 选项卡的默认样式

mysql - 使用 Passport.js 、 React js 、 MySQL 进行用户注册和登录系统

reactjs - 在 react 事件冒泡中使用 e.preventDefault 取消轮子事件

javascript - 如何将初始状态作为我的高阶组件的 Prop 传递?

javascript - 获取每个元素的所有后代

javascript - 如何在 Recompose 中使用 withHandlers 向功能组件添加引用并在 ScrollView 上调用 ScrollTo?

reactjs - WithProps 与 withHandlers