我有一个像这样的小演示组件:
function MyList({data, uppercaseMe, lowercaseMe}) {
return <ul>
{data.map(item =>
<li>{item} -
<button onClick={() => uppercaseMe(item)}>Uppercase me!</button>
<button onClick={() => lowercaseMe(item)}>Lowercase me!</button>
</li>)}
</ul>;
}
然后我想用三个 HOC 来装饰 MyList:
const WithData = (Component) => {
return class extends React.Component {
constructor(props) {
super(props);
this.state= {data:['one', 'two', 'three', 'four', 'five']};
};
render() {
return <Component {...this.props} data={this.state.data} />;
}
}
};
const WithUppercase = (Component) => {
return class extends React.Component {
uppercaseMe = (item) => {
// how to access WithData state from here?
console.log(item.toUpperCase());
};
constructor(props) {
super(props);
};
render() {
return <Component {...this.props} uppercaseMe={this.uppercaseMe}/>;
}
}
};
const WithLowercase = (Component) => {
return class extends React.Component {
lowercaseMe = (item) => {
// how to access WithData state from here?
console.log(item.toLowerCase());
};
constructor(props) {
super(props);
};
render() {
return <Component {...this.props} lowercaseMe={this.lowercaseMe}/>;
}
}
};
像这样:
const ComposedList = WithLowercase(WithUppercase(WithData(MyList)));
不幸的是,我不知道如何从 WithLowercase 或 WithUppercase 中更改 WithData 的状态。
如何将一个 HOC 的状态公开给链中的其他 HOCS?
您不想直接暴露状态。您真正想要做的是将函数作为道具传递给包装的组件,该组件将允许您更新状态。
因此,如果我们采用 HOC 并添加一点代码,创建一个函数来更新其状态,现在可以将其传递给其子组件:
const WithData = (Component) => {
return class extends React.Component {
constructor(props) {
super(props);
this.state= {data:['one', 'two', 'three', 'four', 'five']};
}
update (data) {
this.setState({ data });
}
render() {
return <Component onUpdate={this.update} {...this.props} data={this.state.data} />;
}
}
};
现在,在子组件之一中,我们可以使用它:
const WithUppercase = (Component) => {
return class extends React.Component {
uppercaseMe = (item) => {
const itemIndex = this.props.data.indexOf(item);
const newData = this.props.data.slice();
newData[itemIndex] = item.toUpperCase();
this.props.onUpdate(newData); // update WithData state here
};
constructor(props) {
super(props);
};
render() {
// onUpdate function is once again passed to child components
// implicitly through props if you need to call it again
return <Component {...this.props} uppercaseMe={this.uppercaseMe}/>;
}
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)