您现在的位置是:网站首页> 编程资料编程资料
React高阶组件的使用浅析_React_
2023-05-24
571人已围观
简介 React高阶组件的使用浅析_React_
在学习高阶组件前,首先我们了解一下高阶函数
高阶函数
把一个函数作为另一个函数的参数,那么这个函数就是高阶函数
高阶组件
一个组件的参数是组件,并且返回值是一个组件,我们称这类组件为高阶组件
react常见的高阶函数
withRouter()
memo()
react-redux中connect
高阶组件形式
React中的高阶组件主要有两种形式:属性代理和反向继承
属性代理:一个函数接收一个WrappedComponent组件作为参数传入,并返回一个继承React.Component组件的类,且在该类的render()方法中返回被传入的WrappedComponent组件
反向继承:是一个函数接收一个WrappedComponent组件作为参数传入,并返回一个继承了该传入的WrappedComponent组件的类,且在该类的render()方法中返回super.render()方法
注意:反向继承必须使用类组件,因为函数组件没有this指向
属性继承方式的代码
function Goods(props) { console.log(props); return ( Hello Js
) } //高阶组件的代码, 属性代理的方式 function Color(WrapperComponent){ return class Color extends React.Component{ render(){ console.log(this.props) let obj = {color:"#0088dd"} return ( ) } } } export default Color(Goods);高阶组件我们也可以把他进行单独的剥离出来,然后把他在各个组件中使用
HOC.js文件
import React from 'react'; //高阶组件的代码, 属性代理的方式 export default function Mouse(WrapperComponent){ return class Mouse extends React.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 ( ) } } }goods.js文件
import Mouse from "../context/HOC"; function Goods(props) { console.log(props); let {x,y} = props; return ( 鼠标坐标:x:{x},y:{y} Hello Js
) } export default Mouse(Goods);到此这篇关于React高阶组件的使用浅析的文章就介绍到这了,更多相关React高阶组件内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
