React Recompose 调用增强组件的绑定方法
React Recompose call a bound method of an enhaced component
使用重组是否可以调用增强组件的绑定方法?例如下面例子中 "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 但我不知道如何将其用于绑定方法。
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
使用重组是否可以调用增强组件的绑定方法?例如下面例子中 "SomeOtherComponent"
的 onClickclass 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 但我不知道如何将其用于绑定方法。
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