Changed the working environment, contacted the brand-new project, opened the react project, well… full of stateless components, a little tidy up related information. This time to introduce the use of stateless components, often used in conjunction with Higher Order Components, before seeing the “high-order components” block, misunderstood by his name, in fact, not high-order, he is just a function letter The formula, accepts the parameter element and returns the new element. The simple example is as follows.

React official explanation - A higher-order component is a function that accepts a component and returns a new component.

react

Ps. The following miscellaneous use of es6 deconstruction, Spread Operator (Spread Operator) writing, handling a large number of props in react is very convenient.

1
2
3
4
5
6
7
8
9
10
11
12
13
//stateless component presets props as arguments
function NameCard(props){
return <h2>Hello,{props.name}</h2>
}

//The element that receives a parameter and then adds props returns the element that added the props
function Warpper(Item){
const props = {name:'Chu'}
return <Item {...props}/>
}
const element = Warpper(NameCard);

ReactDOM.render(element, document.getElementById('root'));


example link

ps.es6 arrow function return function logic

1
2
3
4
5
6
7
8
9
10
const Wrapper = (a) => (b)=>{
console.log(a,b)
}

// babel compile
var Wrapper = function Wrapper(a) {
return function (b) {
console.log(a, b);
};
};

Then use return function to pass additional data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//create Person object
function Person(props) {
const {name,age,status} = props;
return <h1>Hello, {name} is {age} years old,ohhh and so {status}</h1>;
}

//create wrapper function
const Warpper = (child) => (props)=>{
//加入物件 status 判斷age 大於18 true=>產生old false =>產生young
props = {...props, status: props.age>18?'old':'young'};
return (
child({...props})
)
}

const person1 = {name:'ian',age:28};
const element = Warpper(Person)(person1);

ReactDOM.render(element, document.getElementById('root'));


example link

The core concept is to wrap components around the attributes we want to add, such as props, lifecycle, and so on. We can use functions shared by many components to organize and create a function that is specifically designed to handle HOC, and then reuse each component. Redux’s connect is also the concept of using HOC. MapStateToProps and mapDispatchToProps are passed to the component as the props we want.

The main reason is that the Internet does not see the introduction of the stateless component, so why not write this to explain what the HOC is doing.

If there is any error in the above, then you have to worry about leaving a message. thank!