高階函數(shù)
在講高階組件之前棉安,先講一下高階函數(shù)這個概念。接受一個函數(shù)為參數(shù)幔嫂,或者返回結果為函數(shù)的函數(shù)纱昧,就是一個高階函數(shù)跪楞。
下面的greaterThan就是一個高階函數(shù):
const greaterThan = (n) => {
return (m) => m > n;
}
let greaterThan10 = greaterThan(10);
let isGreaterThan = greaterThan10(11);
// isGreaterThan: true
那么什么是高階組件呢缀去?
接受一個組件為參數(shù),并且返回一個新組件的組件甸祭。
const EnhancedComponent = higherOrderComponent(WrappedComponent);
React官方文檔中的例子:
const CommentListWithSubscription = withSubscription(
CommentList, // 被包裹的組件
(DataSource) => DataSource.getComments() // 作為props傳入的數(shù)據(jù)
);
const BlogPostWithSubscription = withSubscription(
BlogPost, // 被包裹的組件
(DataSource, props) => DataSource.getBlogPost(props.id) // 作為props傳入的數(shù)據(jù)
);
// ---- 高階組件 ------------------------------------------
// 接受一個組件WrappedComponet作為參數(shù)
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)
};
}
componentDidMount() {
// 橫切關注點(cross-cutting concerns缕碎,面向切面編程)
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
// 橫切關注點
DataSource.removeChangeListener(this.handleChange);
}
// 橫切關注點
handleChange() {
this.setState({
data: selectData(DataSource, this.props)
});
}
render() {
// 給包含的組件傳遞數(shù)據(jù)
// 注意,所有的props里的東西都要傳遞給被包裹的組件
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}
最常見的高階組件的方法簽名就像下面這樣:
// React Redux的`connect`方法
const ConnectedComment = connect(commentSelector, commentActions)(CommentList);
為了更便于理解池户,上面的代碼可以分解為兩步:
// connect函數(shù)的返回結果是另一個函數(shù)
const enhance = connect(commentListSelector, commentListActions);
// 這個返回的函數(shù)是一個高階組件咏雌,它返回一個與Redux的store關聯(lián)的一個組件
const ConnectedComment = enhance(CommentList);
換言之,connect是一個返回一個高階組件的高階函數(shù)! :)
看看 官方文檔 更詳細