【问题标题】:React Recompose call a bound method of an enhaced componentReact Recompose 调用增强组件的绑定方法
【发布时间】:2018-09-27 10:39:28
【问题描述】:

使用 recompose 是否可以调用增强组件的绑定方法?例如下面“SomeOtherComponent”示例上的 onClick

class BaseComponent extends Component {
  constructor (props) {
    super(props)
    this.myBoundMethod = this._myBoundMethod.bind(this)
  }
  _myBoundMethod () {
    return this.something
  }
  render () {
    return (<h1>{'Example'}</h1>)
  }
}

const Enhaced = compose(
  /* Any number of HOCs ...  
    lifecycle,
    withProps,
    withStateHandlers
  */
)(BaseComponent)

class SomeOtherComponent extends Component {
  constructor (props) {
    super(props)
    this.handleClick = this._handleClick.bind(this)
  }
  _handleClick () {
    console.log(this._enhacedComponent.myBoundMethod())
  }
  render () {
    <div>
      <Enhaced ref={(c) => {this._enhacedComponent = c}} />
      <button onClick={this.handleClick}>Click</Button>
    </div>
  }
}

我知道hoistStatics,但我不知道如何将其用于绑定方法。

【问题讨论】:

    标签: reactjs recompose


    【解决方案1】:

    hoistStatics 只提升静态属性,但您需要的是实例方法。

    这是一种在 Recompose 中实现所需内容的方法。首先,将ref回调重命名为,例如forwardedRef

    <Enhaced fowardedRef={(c) => { this._enhacedComponent = c }} />
    

    然后,使用 withProps 作为最后一个 HOC 将 fowardedRef 重命名为 ref

    const Enhaced = compose(
      /* ... other HOCs ... */
      withProps(({ fowardedRef }) => ({ ref: fowardedRef  }))
    )(BaseComponent)
    

    现在,ref 回调被传递给 BaseComponent

    整个运行示例在这里https://codesandbox.io/s/6y0513xpxk

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 2019-02-04
      • 1970-01-01
      • 2019-01-25
      • 2023-03-31
      • 2015-09-11
      相关资源
      最近更新 更多