当前位置:网站首页>高阶组件使用
高阶组件使用
2022-08-10 10:09:00 【是张鱼小丸子鸭】
目录
在学习高阶组件前,首先我们了解一下高阶函数
高阶函数?
把一个函数作为另一个函数的参数,那么这个函数就是高阶函数
高阶组件?
一个组件的参数是组件,并且返回值是一个组件,我们称这类组件为高阶组件
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 (
<div className="box1">
<h3 style={
{color:props.color}}>Hello Js</h3>
</div>
)
}
//高阶组件的代码, 属性代理的方式
function Color(WrapperComponent){
return class Color extends React.Component{
render(){
console.log(this.props)
let obj = {color:"#0088dd"}
return (
<WrapperComponent {...this.props} {...obj}/>
)
}
}
}
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 (
<WrapperComponent {...this.props} {...this.state}/>
)
}
}
}
goods.js文件
import Mouse from "../context/HOC";
function Goods(props) {
console.log(props);
let {x,y} = props;
return (
<div className="box1">
<div>
鼠标坐标:x:{x},y:{y}
</div>
<h3 >Hello Js</h3>
</div>
)
}
export default Mouse(Goods);
边栏推荐
猜你喜欢
Development environment variable record under win
阻塞队列与线程池原理
"Chief Engineer" Principal (Principal) engineer's way of training
"Data Strategy" Results-Driven Enterprise Data Strategy: Organization and Governance
bus event bus use
Situation丨The intrusion of hackers intensifies, and the shooting range sets up a "defense shield" for network security
MySQL executes the query process
CentOS和Ubantu的Mysql主从配置
Array of shell scripts
首次入选OSDI顶会!腾讯提出超大规模推荐系统的模型低延时更新方案
随机推荐
ECCV 2022 | 视频理解新框架X-CLIP:仅用微调的成本,达到预训练的全能
武功修炼:内功
"Chief Engineer" Principal (Principal) engineer's way of training
dedecms supports one-click upload of Word content
database constraints
自动化测试及Selenium
91.(cesium之家)cesium火箭发射模拟
web项目访问引用jar内部的静态资源
3D旋转文本动画js特效
CSDN 21 Days Learning Challenge - Polymorphism (05)
The web project accesses static resources inside the reference jar
LCD模块如何建立联系分析
「业务架构」TAGAF建模:业务服务/信息图
网络安全笔记5——数字签名
【数据架构】概念数据模型和逻辑数据模型有什么区别
PPT | 「课件」企业中高层人员安全管理培训(118页)
C#List的使用以及Linq的使用
【微服务架构】微服务与SOA架构(2)
ESP8266-Arduino编程实例-MQ-9 一氧化碳可燃气体传感器驱动
2022.8.9-----leetcode.1413