1. Basic Concepts
Component to high-order component is a parameter, the function returns a value of the new component.
2 illustrates
① decoration factory pattern
Component is the basic unit react in, there is usually some logical component (non-rendering) required multiplexing processing. Here we can encapsulate some of the internal components in common with the higher-order components.
When unencapsulated, you can not reuse the same logic:
Render comments list
class CommentList extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { // assumed "DataSource" is a data source variable within a global scope comments: DataSource.getComments() }; } componentDidMount() { // Subscribe to changes DataSource.addChangeListener(this.handleChange); } componentWillUnmount() { // Clear subscription DataSource.removeChangeListener(this.handleChange); } act change () { // When updating the data source, the update component status this.setState({ comments: DataSource.getComments() }); } render() { return ( <div> {this.state.comments.map((comment) => ( <Comment comment={comment} key={comment.id} /> ))} </div> ); } }
Rendering blog list
lass 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); } act change () { this.setState({ blogPost: DataSource.getBlogPost(this.props.id) }); } render() { return <TextBlock text={this.state.blogPost} />; } }
Borrow higher order component, a common logical package:
const CommentListWithSubscription = withSubscription( CommentList, (DataSource) => DataSource.getComments() ); const BlogPostWithSubscription = withSubscription( BlogPost, (DataSource, props) => DataSource.getBlogPost(props.id) );
Processing components (processing: Processing common logical) plant, the old receiving component, the new component Returns:
// This function receives a component ... function withSubscription(WrappedComponent, selectData) { // ... and return to another component ... return class extends React.Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.state = { data: selectData(DataSource, props) }; } componentDidMount() { // ... responsible for the subscription-related operations ... DataSource.addChangeListener(this.handleChange); } componentWillUnmount() { DataSource.removeChangeListener(this.handleChange); } act change () { this.setState({ data: selectData(DataSource, this.props) }); } render() { // ... and use the new data rendering components are packed! // Note that we may also transfer other property return <WrappedComponent data={this.state.data} {...this.props} />; } }; }
233