基本信息
文件名称:React高阶组件的使用浅析.docx
文件大小:15.96 KB
总页数:3 页
更新时间:2025-05-22
总字数:约1.5千字
文档摘要

React高阶组件的使用浅析

目录高阶函数高阶组件react常见的高阶函数高阶组件形式在学习高阶组件前,首先我们了解一下高阶函数

高阶函数

把一个函数作为另一个函数的参数,那么这个函数就是高阶函数

高阶组件

一个组件的参数是组件,并且返回值是一个组件,我们称这类组件为高阶组件

react常见的高阶函数

withRouter()

memo()

react-redux中connect

高阶组件形式

React中的高阶组件主要有两种形式:属性代理和反向继承

属性代理:一个函数接收一个WrappedComponent组件作为参数传入,并返回一个继承React.Component组件的类,且在该类的render()方法中返回被传入的WrappedComponent组件

反向继承:是一个函数接收一个WrappedComponent组件作为参数传入,并返回一个继承了该传入的WrappedComponent组件的类,且在该类的render()方法中返回super.render()方法

注意:反向继承必须使用类组件,因为函数组件没有this指向

属性继承方式的代码

functionGoods(props){

console.log(props);

return(

divclassName=box1

h3#0088dd}

return(

WrapperComponent{...ps}{...obj}/

exportdefaultColor(Goods);

高阶组件我们也可以把他进行单独的剥离出来,然后把他在各个组件中使用

HOC.js文件

importReactfromreact;

//高阶组件的代码,属性代理的方式

exportdefaultfunctionMouse(WrapperComponent){

returnclassMouseextendsReact.Component{

constructor(props){

super(props);

this.state={

x:0,

y:0,

this.getMouse();

getMouse=()={

document.addEventListener(mousemove,(event)={

this.setState({

x:event.clientX,

y:event.clientY

render(){

//console.log(this.state);

return(

WrapperComponent{...ps}{...this.state}/

}

goods.js文件

importMousefrom../context/HOC;

functionGoods(props){

console.log(props);

let{x,y}=props;

return(

divclassName=box1

div

鼠标坐标:x:{x},y:{y}

/div

h3HelloJs/h3

/div

exportdefaultMouse(Goods);