React高階組件的使用淺析
在學(xué)習(xí)高階組件前,首先我們了解一下高階函數(shù)
高階函數(shù)
把一個函數(shù)作為另一個函數(shù)的參數(shù),那么這個函數(shù)就是高階函數(shù)
高階組件
一個組件的參數(shù)是組件,并且返回值是一個組件,我們稱這類組件為高階組件
react常見的高階函數(shù)
withRouter()
memo()
react-redux中connect
高階組件形式
React中的高階組件主要有兩種形式:屬性代理和反向繼承
屬性代理:一個函數(shù)接收一個WrappedComponent組件作為參數(shù)傳入,并返回一個繼承React.Component組件的類,且在該類的render()方法中返回被傳入的WrappedComponent組件
反向繼承:是一個函數(shù)接收一個WrappedComponent組件作為參數(shù)傳入,并返回一個繼承了該傳入的WrappedComponent組件的類,且在該類的render()方法中返回super.render()方法
注意:反向繼承必須使用類組件,因為函數(shù)組件沒有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);高階組件我們也可以把他進(jìn)行單獨的剝離出來,然后把他在各個組件中使用
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>
鼠標(biāo)坐標(biāo):x:{x},y:{y}
</div>
<h3 >Hello Js</h3>
</div>
)
}
export default Mouse(Goods);到此這篇關(guān)于React高階組件的使用淺析的文章就介紹到這了,更多相關(guān)React高階組件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React+Typescript創(chuàng)建項目的實現(xiàn)步驟
通過React組件庫和TypeScript的強(qiáng)類型特性,開發(fā)者可以創(chuàng)建出具有優(yōu)秀用戶體驗和穩(wěn)定性的Web應(yīng)用程序,本文主要介紹了React+Typescript創(chuàng)建項目的實現(xiàn)步驟,感興趣的可以了解一下2023-08-08
使用react+redux實現(xiàn)計數(shù)器功能及遇到問題
使用redux管理數(shù)據(jù),由于Store獨立于組件,使得數(shù)據(jù)管理獨立于組件,解決了組件之間傳遞數(shù)據(jù)困難的問題,非常好用,今天重點給大家介紹使用react+redux實現(xiàn)計數(shù)器功能及遇到問題,感興趣的朋友參考下吧2021-06-06
在React中寫一個Animation組件為組件進(jìn)入和離開加上動畫/過度效果
這篇文章主要介紹了在React中寫一個Animation組件為組件進(jìn)入和離開加上動畫/過度效果,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06

