日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React高階組件的使用淺析_React

作者:是張魚小丸子鴨 ? 更新時間: 2022-10-09 編程語言

在學習高階組件前,首先我們了解一下高階函數

高階函數

把一個函數作為另一個函數的參數,那么這個函數就是高階函數

高階組件

一個組件的參數是組件,并且返回值是一個組件,我們稱這類組件為高階組件

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

欄目分類
最近更新