打印日志的高阶组件实现和链式调用

710 阅读1分钟

你这哪里是链式调用,这是套娃调用。

import React, { Component } from 'react';
//高阶组件:不是组件,本质上是一个函数,这个函数它接收一个组件或者多个组件,返回一个新的组件,Comment为高阶组件
//高阶函数
//定义:接收的参数是函数或者返回值是函数
//常见的:数组遍历的相关方法、定时器、promise、高阶组件
//作用:实现一个更加强大的动态功能
// const highOrderCom = (Comp)=>{
// // 返回一个新组件
// const NewComponent = (props)=>{
// //属性代理
// const attr = {type:'高阶组件',price:'1999'}
// return <Comp {...props} {...attr}></Comp>
// }
// return NewComponent
// }
// 打印日志的高阶组件
const witchLOg = (Comp)=>{
console.log(Comp.name+'渲染了');
const newCom = (props)=>{
return <Comp {...props}></Comp>
}
return newCom;
}
const highOrderCom = (Comp)=>{
return class extends Component{
constructor(props){
super(props);
}
componentDidMount(){
console.log('发起ajax请求')
}
handleClick=()=>{

}
render(){
return(
//属性代理是最常见的实现方式
<Comp{...this.props} name='react' content='高阶组件的使用' onClick={this.handleClick}></Comp>
)
}
}
}
class Hoc extends Component {
render() {
return (
<div>
<h3>当前课程:{this.props.name}</h3>
<h3>当前价格:{this.props.content}</h3>
</div>
);
}
}
//链式调用
export default highOrderCom(witchLOg(witchLOg(Hoc)))

/*
1.为什么我们需要高阶组件?
react中的高阶组件能写出易于维护的react代码,减少时间。
2.高阶组件是什么?
本质上是一个函数,这个函数它接收一个组件或者多个组件,返回一个新的组件,
3.如何实现高阶组件
属性代理是最常见的实现方式 还有一个反向继承
好处:常用的方法独立出来并多次复用
4.高阶组件的应用
1.代码复用
2.权限的控制
3.打印日志
*/