高階元件是react中用于重用元件邏輯的進階技術。可以說是一種模式。具體來說呢,高階元件是一個函數,它接收一個元件并傳回一個新的元件。
就像這樣,
const EnhancedComponent = higherOrderComponent(WrappedComponent);
我們知道,元件将props轉為UI,而高階元件是将一個元件轉為另一個元件。元件是React中代碼重用的最小單元。然而你會發現某些模式并不能直接适應傳統元件。
我們可以寫一個函數,能夠建立類似于
CommentList
和
BlogPost
這類訂閱
DataSource
的新的元件。這個函數接受一個子元件作為參數,這個子元件接受訂閱資料源作為props,調用
withSubscription
如下,
const CommentListWithSubscription = withSubscription(
CommentList,
(DataSource) => DataSource.getComments()
);
const BlogPostWithSubscription = withSubscription(
BlogPost,
(DataSource, props) => DataSource.getBlogPost(props.id)
);
第一個參數是被包含的元件,第二個參數根據給定的
DataSource
和目前的props取回我們需要的資料。
當
CommentListWithSubscription
和
CommentListWithSubscription
被渲染時,
CommentList
和
BlogPost
将會被傳遞
data
屬性,其中包含從
DataSource
取回的最新資料。
// 函數接受一個元件參數……
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() {
// ……注意訂閱資料……
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
this.setState({
data: selectData(DataSource, this.props)
});
}
render() {
// ……使用最新的資料渲染元件
// 注意此處将已有的props屬性傳遞給原元件
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}
高階元件既不會修改輸入元件,也不會通過繼承來複制行為。相反,通過包裹的形式,高階元件将原先的元件組合在container元件中。高階元件是純函數,沒有副作用。
在react-router4.0中我們使用的withRouter就是一個高階元件,以及redux中的connect等。
轉載于:https://www.cnblogs.com/zyl-Tara/p/9719458.html