GitHub learning Demo.
High-order components are the main implementation of reusable components in React. But the higher-order component itself isn’t the React API; it’s just a pattern.
Specifically, a higher-order component is a function that takes a component as an argument and returns a new component.
function Section() {
return <section>Section</section>
}
function higherOrderComponent(BasicalComponent) {
return (
<artical>
<header>Header</header>
<hr>
<BasicalComponent />
<hr>
<footer>Footer</footer>
</artical>
);
}
const Paga1 = higherOrderComponent(Section);
Copy the code
Note that higher-order components neither modify the input component nor copy its behavior using inheritance. Instead, high-order components composes the original components by wrapping them with a container component. A higher-order component is a pure function with no side effects.
Simply put, this is to output a new, more functional component without contaminating the input component.
function Button(props) {
return <button onClick={props.onClick}>{props.children}</button>
}
function setClickCounter(Component, config = {}) {
return class extends React.Component {
constructor(porps) {
super(porps);
const {name, id, completeTime} = config;
this.clicked = this.clicked.bind(this);
this.state = {
name,
id,
completeTime,
count: 0,
isFinished: false}}clicked() {
if (this.state.isFinished) return;
const {name, id, completeTime} = this.state;
this.setState(preState => {
const count = preState.count +1;
const isFinished = count >= completeTime;
console.log(`"${name}"Click on the${count}/${completeTime}Time [${isFinished? 'Done ':' not done '}] `);return {count, isFinished};
});
}
render() {
const {name, isFinished} = this.state;
const {children, otherProps} = this.props;
if (isFinished) return `${name}[Completed]. `;return( <Component onClick={this.clicked} {... otherProps}> {children} </Component> ); } } } const SuperBtnA =setClickCounter(Button, {
name: 'A Click event ',
id: 'A',
completeTime: 10,
});
const SuperBtnB = setClickCounter(Button, {
name: 'B Click event ',
id: 'B',
completeTime: 15,
});
Copy the code