網站首頁 編程語言 正文
在學習高階組件前,首先我們了解一下高階函數
高階函數
把一個函數作為另一個函數的參數,那么這個函數就是高階函數
高階組件
一個組件的參數是組件,并且返回值是一個組件,我們稱這類組件為高階組件
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);
原文鏈接:https://blog.csdn.net/qq_60976312/article/details/126191256
相關推薦
- 2024-03-23 如何保證Redis和數據庫數據一致性
- 2022-06-30 Oracle在PL/SQL中使用子查詢_oracle
- 2023-05-06 MacOS安裝python報錯"zsh:?command?not?found:python"的解決方
- 2022-09-08 詳解Dijkstra算法原理及其C++實現_C 語言
- 2022-10-02 利用Android封裝一個有趣的Loading組件_Android
- 2022-09-06 詳解SQL?Server?中的?ACID?屬性_MsSql
- 2022-08-08 python中Pytest常用的插件_python
- 2022-07-13 查看nginx連接數
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支