向React中的高阶组件添加方法
Add methods to Higher Order Components in React
据我所知,ReactJS中的HOC会为您的装饰组件添加道具,但我想添加也可以作用于state
的方法
例如,如果不首先检查this.isMounted()
,我通常从不调用this.setState()
。本质上,我想要:
export default ComposedComponent => class BaseComponent extends React.Component {
static displayName = "BaseComponent";
constructor(props) {
super(props);
}
//------> I want this method to be available to any ComposedComponent
//------> And it has to act upon the state of ComposedComponent
updateState(obj) {
if (this.isMounted() && obj) {
this.setState(obj);
}
}
render() {
return (
<ComposedComponent {...this.props} {...this.state} />
)
}
}
说我想装饰我的组件Home
。所以我只将其作为export default BaseComponent(Home)
返回。
但this.updateState()
在Home
类中不可用。我该如何解决此问题?
好吧,我想明白了。我在这上面花了太多时间,所以我希望这个答案也能帮助到一些人。简单回答:将decorator中的方法添加到props
,然后将其绑定到decorated类的构造函数中。
这是代码:
export default ComposedComponent => class BaseComponent extends React.Component {
static displayName = "BaseComponent";
constructor(props) {
super(props);
// Note how I am adding this to state
// This will be passed as a prop to your composed component
this.state = {
updateState: this.updateState
}
}
updateState(obj) {
this.setState(obj);
}
render() {
return (
<ComposedComponent {...this.props} {...this.state} />
)
}
}
下面是一个使用它的类的例子(为了简单起见,我使用ES7
):
@BaseComponent
class Home extends React.Component {
static displayeName = 'Home';
constructor(props) {
super(props);
// And here I am binding to it
this.updateState = this.props.updateState.bind(this);
}
render() {
return (
<div>Hi</div>
)
}
}
相关文章:
- 如何定义组件添加到DataItem的顺序
- React:向现有组件添加道具
- 向React中的高阶组件添加方法
- 在 React 中向组件添加新输入并跟踪状态
- Angular2 - 尝试将组件从父组件添加到子组件中
- extjs4 - 将自定义组件添加到容器
- 将react组件添加到contenteditable或innerhtml
- 反应多个组件添加项目
- 如何向 ReactJS 组件添加多个类
- 可以't将组件添加到dojox/layout/GridContainer
- KnockoutJs组件-添加默认类
- 如何使用React.js而不是JQuery.js克隆React组件(添加到其他地方)
- 向动态创建的组件添加事件绑定
- 如何在rteplugins下为richtext组件添加图像插件
- 为每个reactJS组件添加组件
- 如何向父窗口的组件添加字符
- React:如何给库中的组件添加一个props
- Highcharts提示?如何向hiccharts DOM组件添加类或id ?
- 用于向组件添加多个订阅的React mixin
- 如何在vue.js中为动态组件添加道具