September 29,2021
高阶组件是参数为组件,返回值为新组件的函数。
他把组件中可以复用的逻辑提取出来作为一个抽象组件。如果某个组件需要这段逻辑,就用高阶组件*套在*它的外面来形成一个新的组件,这个组件拥有自己的逻辑和一些高阶组件的逻辑。const HocComponent = WithHoc(originComponent)
。HocComponent
就是对外的组件名了。HOC 是纯函数,没有副作用。他是一个普通函数,可以根据需要对参数进行增添或者删除。
// withSubscription是一个高阶组件,CommentList 和 BlogPost 是需要用到这段逻辑的组件。第二个参数是定制的部分,是两个组件中不同的地方。
const CommentListWithSubscription = withSubscription(
CommentList,
(DataSource) => DataSource.getComments()
);
const BlogPostWithSubscription = withSubscription(
BlogPost,
(DataSource, props) => DataSource.getBlogPost(props.id)
);
// 此函数接收一个组件...
function withSubscription(WrappedComponent, selectData) {
// ...并返回另一个组件...
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(DataSource, props) // 假设 "DataSource" 是个全局范围内的数据源变量
};
}
componentDidMount() {
// ...负责订阅相关的操作...
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
this.setState({
data: selectData(DataSource, this.props)
});
}
render() {
// ... 并使用新数据渲染被包装的组件!
// 请注意,我们可能还会传递其他属性
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}
如果HOC需要使用传给该组件的props,就用以下方法用。
render() {
// 过滤掉非此 HOC 额外的 props,且不要进行透传
const { extraProp, ...passThroughProps } = this.props;
// 将 props 注入到被包装的组件中。
// 通常为 state 的值或者实例方法。
const injectedProp = someStateOrInstanceMethod;
// 将 props 传递给被包装组件
return (
<WrappedComponent
injectedProp={injectedProp}
{...passThroughProps}
/>
);
}
上一篇
下一篇