Preface:
because mixin is contrary to JavaScript semantics, React ES6 uses higher-order components instead of mixins.
In This section, we will focus on how to replace the traditional React mixins with higher-order components. How do we use ES6 to handle mixin?
What is a high-order component?
Adding logic to an existing component class through a function is a higher-order component.
A higher-order component is actually just a method that uses an existing component to return another component that wraps it. Let's take a look at how React ES6 achieves mixin.
Import React from ' React ';
1, introduce Hightercomponet method
import {hightercomponet} from './hightercomponet ';
Class Example extends React.component {
//... A little ...
}
2, export higher-order components packaging enhanced Example
export default hightercomponet (Example);
Parsing: We put some common logic processing into the Hightercomponet method, and the Example component needs to use the logic processing. After the above processing, the export of the Example component contains the logical processing of hightercomponet, Example becomes a higher-order component (higher-order function-callback function).
Then let's take a look at the contents of Hightercomponet:
Import {Component} from "React";
Export Const Hightercomponet = (composedcomponent) = Class extends Component {
constructor () {
this.state = { Data:null};
}
Componentdidmount () {
this.setstate ({data: ' Hello '});
}
Render () {
return <composedcomponent {... this.props} data={this.state.data}/>;
}
};
Hightercomponet is a component of a method that is a parameter of his. When a Component is passed in, it is automatically extended for the Component and returns the new class definition.
In the example above, an extended Component class is returned, the state is added to the constructor, and the processing logic is added to the React life cycle function Componentdidmount, and the Render method uses the passed parameters to complete the rendering.
Let's look back at the Example components:
Import {Component} from "React";
Import {hightercomponet} from "./hightercomponet";
Class Example = Class extends Component {
render () {
if (!this.props.data) return <div>waiting...</div& gt;;
Return <div>{this.data}</div>;
}
}
Example only know that others will pass the data through the This.prop.data, others will not care. As you can see, Example is much easier to work with than the mixins extension.