高阶函数
高阶函数本质是一个函数,参数是一个组件,经过处理后再返回一个组件。
高阶函数的功能:强化props,条件渲染,赋能组件(生命周期的劫持,事件的劫持,打印日志)
编写高阶函数
强化props
通过高阶函数注入数据到组件中,那么在使用组件时,就不需要手动传入数据。
propsHoc.js
import React from "react";
export default function propsHoc(Comp) {
return class WrapperedComp extends React.Component {
render() {
return (
<Comp msg='嘻嘻' />
)
}
}
}
抽离state
在高阶组件里面修改state数据,达到抽离state的作用。
propsHoc.jsx
import React from "react";
export default function propsHoc(Comp) {
return class WrapperedComp extends React.Component {
state = {
msg: '嘻嘻'
}
changeMsg = () => {
console.log('changeMsg');
this.setState({
msg: 'web前端'
})
}
render() {
return (
<Comp msg={this.state.msg} changeMsg={this.changeMsg} />
)
}
}
}
条件渲染
在高阶函数里面判断是否要渲染参数组件,达到条件控制。
ifHoc.jsx
import React from "react";
export default function ifHoc(Comp) {
return class WrapperedComp extends React.Component {
render() {
const token = localStorage.getItem('token')
return (
<>
{
token ? <Comp /> : <></>
}
</>
)
}
}
}
If.jsx
import React, { Component } from 'react'
import ifHoc from './ifHoc'
class If extends Component {
render() {
return (
<div>If</div>
)
}
}
export default ifHoc(If)
打印日志
可以将生命周期中的打印日志操作放到高阶组件中去执行。
import React from 'react';
export default function lifeHoc(Comp) {
return class WrapperdComp extends React.Component {
componentDidMount() {
console.log('打印日志');
}
render() {
return (
<Comp />
)
}
}
}
反向继承-生命周期拦截
高阶组件可以直接继承自参数组件,这就是反向继承。
import React from "react";
export default function extHoc(Comp) {
let didMount = Comp.prototype.componentDidMount;
return class WrapperedComp extends Comp {
componentDidMount() {
console.log('WrapperedComp didmount');
if (didMount) {
didMount();
}
}
render() {
return super.render()
}
}
}
事件劫持
高阶组件事件劫持。
import React from "react";
export default function eventHoc(Comp) {
return class WrapperedComp extends React.Component {
click = () => {
console.log('click');
}
render() {
return (
<div onClick={this.click}>
<Comp />
</div>
)
}
}
}