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);
高階組件我們也可以把他進行單獨的剝離出來,然后把他在各個組件中使用
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 Native自定義Android的SSL證書鏈校驗
這篇文章主要為大家介紹了React Native自定義Android的SSL證書鏈校驗示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10React render核心階段深入探究穿插scheduler與reconciler
這篇文章主要介紹了React render核心階段穿插scheduler與reconciler,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-11-11使用react-beautiful-dnd實現(xiàn)列表間拖拽踩坑
相比于react-dnd,react-beautiful-dnd更適用于列表之間拖拽的場景,本文主要介紹了使用react-beautiful-dnd實現(xiàn)列表間拖拽踩坑,感興趣的可以了解一下2021-05-05react?echarts?tree樹圖搜索展開功能示例詳解
這篇文章主要為大家介紹了react?echarts?tree樹圖搜索展開功能示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01React Native基礎(chǔ)入門之初步使用Flexbox布局
React中引入了flexbox概念,flexbox是屬于web前端領(lǐng)域CSS的一種布局方案,下面這篇文章主要給大家介紹了關(guān)于React Native基礎(chǔ)入門之初步使用Flexbox布局的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-07-07