1.在React中higher-order component (HOC)是一種重用組件邏輯的高級技術(shù)。HOC不是React API中的一部分。HOC是一個函數(shù),該函數(shù)接收一個組件并且返回一個新組件。在React中,組件是代碼復(fù)用的基本單位。
2.為了解釋HOCs,舉下面兩個例子
CommentList組件會渲染出一個comments列表,列表中的數(shù)據(jù)來自于外部。
class CommentList extends React.Component { constructor() { super(); this.handleChange = this.handleChange.bind(this); this.state = { // "DataSource" is some global data source comments: DataSource.getComments() }; } componentDidMount() { // Subscribe to changes DataSource.addChangeListener(this.handleChange); } componentWillUnmount() { // Clean up listener DataSource.removeChangeListener(this.handleChange); } handleChange() { // Update component state whenever the data source changes this.setState({ comments: DataSource.getComments() }); } render() { return ( <div> {this.state.comments.map((comment) => ( <Comment comment={comment} key={comment.id} /> ))} </div> ); } } 接下來是BlogPost組件,這個組件用于展示一篇博客信息
class BlogPost extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { blogPost: DataSource.getBlogPost(props.id) }; } componentDidMount() { DataSource.addChangeListener(this.handleChange); } componentWillUnmount() { DataSource.removeChangeListener(this.handleChange); } handleChange() { this.setState({ blogPost: DataSource.getBlogPost(this.props.id) }); } render() { return <TextBlock text={this.state.blogPost} />; } } 這兩個組件是不一樣的,它們調(diào)用了DataSource的不同方法,并且它們的輸出也不一樣,但是它們中的大部分實(shí)現(xiàn)是一樣的:
1.裝載完成后,給DataSource添加了一個change listener
2.當(dāng)數(shù)據(jù)源發(fā)生變化后,在監(jiān)聽器內(nèi)部調(diào)用setState
3.卸載之后,移除change listener
可以想象在大型應(yīng)用中,相同模式的訪問DataSource和調(diào)用setState會一次又一次的發(fā)生。我們希望抽象這個過程,從而讓我們只在一個地方定義這個邏輯,然后在多個組件中共享。
接下來我們寫一個創(chuàng)建組件的函數(shù),這個函數(shù)接受兩個參數(shù),其中一個參數(shù)是組件,另一個參數(shù)是函數(shù)。下面調(diào)用withSubscription函數(shù)
const CommentListWithSubscription = withSubscription( CommentList, (DataSource) => DataSource.getComments()); const BlogPostWithSubscription = withSubscription( BlogPost, (DataSource, props) => DataSource.getBlogPost(props.id));
調(diào)用withSubscription傳的第一個參數(shù)是wrapped 組件,第二個參數(shù)是一個函數(shù),該函數(shù)用于檢索數(shù)據(jù)。
新聞熱點(diǎn)
疑難解答
圖片精選