react高階組件添加和刪除props
嘮叨幾句啦
在看程墨老師的深入淺出高階組件,開頭一點(diǎn)提了一個(gè)需要,創(chuàng)建兩個(gè)高階組件,一個(gè)能給傳入的元素自定義添加props,一個(gè)是刪除特定的props。我剛剛做了一下,發(fā)現(xiàn)高階組件需要區(qū)分好傳入的是class還是react element, 同時(shí)也需要注意好return回去的是啥。順便提一下高階組件的概念,就說一個(gè)函數(shù),能夠接受一個(gè)組件作為參數(shù),然后返回的時(shí)候,這個(gè)組件就帶有這個(gè)高階組件給的某些特性。我理解就跟掉泥坑了,得帶點(diǎn)土出來一個(gè)道理。
對(duì)比一下兩個(gè)組件,貼代碼時(shí)刻來啦
刪除屬性的高階組件
我們需要傳入任何組件和參數(shù),都把user參數(shù)給刪除了,所以返回值是一個(gè)接收props屬性的函數(shù)。
import React from "react" function removeUserProp(WrappedComponent) { return function newRender(props) { const {user, ...otherProps} = props;// 刪除user這個(gè)屬性值 return <WrappedComponent {...otherProps} /> } } export default removeUserProp
使用的時(shí)候
const RemoveComponent = removeUserProp(reactComponentClass)({user: "aa"});// 這里返回的是一個(gè)react component render () { return <div> {RemoveComponent} </div> }
增加屬性的高階組件
import React from "react" const addNewProps = function (WrappedComponent, newProps) {// 接收的是一個(gè)class作為參數(shù),返回一個(gè)class return class WrappingComponent extends React.Component { render () { return <WrappedComponent {...this.props} {...newProps}/> } } } export default addNewProps
使用的時(shí)候,返回值是class,所以要用<ReactClassName/>轉(zhuǎn)換成可以渲染的react組件
const AddUserComponent = addNewProps(SampleComponent, {user: "aa"}) render () { return <AddUserComponent /> }
完整的使用的例子代碼:
import React from "react" import addNewProps from './addNewProps' import removeUserProp from './removeUserProp' class SampleComponent extends React.Component { constructor(props) { console.log(props) super(props) } render () { console.log(this.props) return <div> { this.props.user ? <p>哈哈哈</p> : <p>哈哈哈2</p> } </div> } } class Test extends React.Component { render () { var obj = {aa: "aa"} const AddUserComponent = addNewProps(SampleComponent, {user: "aa"}) const RemoveUserComponent = removeUserProp(SampleComponent)({user: "aa"}) return <div> <AddUserComponent /> {RemoveUserComponent} </div> } } export default Test
一點(diǎn)點(diǎn)小收獲就是明白了高階組件要看清楚輸入輸出。class跟react element的區(qū)別。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Native?Memory?Tracking追蹤區(qū)域示例分析
這篇文章主要為大家介紹了Native?Memory?Tracking追蹤區(qū)域示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11React.memo函數(shù)中的參數(shù)示例詳解
這篇文章主要為大家介紹了React.memo函數(shù)中的參數(shù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09React實(shí)時(shí)預(yù)覽react-live源碼解析
這篇文章主要為大家介紹了React實(shí)時(shí)預(yù)覽react-live源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08關(guān)于react ant 組件 Select下拉框 值回顯的問題
這篇文章主要介紹了關(guān)于react ant 組件 Select下拉框 值回顯的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08jsoneditor二次封裝實(shí)時(shí)預(yù)覽json編輯器組件react版
這篇文章主要為大家介紹了jsoneditor二次封裝實(shí)時(shí)預(yù)覽json編輯器組件react版示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10React 數(shù)據(jù)獲取與性能優(yōu)化詳解
這篇文章主要為大家介紹了React 數(shù)據(jù)獲取與性能優(yōu)化方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10