您可以为此创建高阶组件(HOC),基本上,您只需使用重复的相同生命周期方法编写组件,然后在render()
函数中,使用您想要的任何 HOC 内部状态参数调用this.props.children
函数,您可以传递整个state
和一个setState
功能,因此您可以更改底层组件内的 HOC 状态。
例如:
class HOC extends React.Component {
constructor(props) {
super(props);
state = {
someState: 'foo',
};
}
componentWillMount() {
console.log('i mounted!')
}
render() {
return (
<div>
{this.props.children({ state: this.state, setState: this.setState })}
</div>
)
}
}
const SomeComponent = () =>
<HOC>
{({ state, setState }) => (
<div>
<span>someState value: </span>
<input
value={state.someState}
onChange={e => setState({ someState: e.target.value})}
/>
</div>
)}
</HOC>
你还可以用它做一些非常酷和有趣的事情,比如在你需要的时候连接你的 redux 状态的一部分:
import { connect } from 'react-redux';
const ProfileState = connect(
state => ({ profile: state.profile }),
null,
)(({
profile,
children
}) => (
<div>
{children({ profile })}
</div>
));
const ProfilePage = () => (
<div>
Your name is:
<ProfileState>
{({ profile }) => (
<span>{profile.name}</span>
)}
</ProfileState>
</div>
);
这是有关此技术的完整文档。