日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

react 给一个引用的组件添加新属性_高阶组件在React中的应用

發布時間:2023/12/10 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 react 给一个引用的组件添加新属性_高阶组件在React中的应用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

高階組件的定義

接受React組件作為輸入,輸出一個新的React組件。

概念源自于高階函數,將函數作為參數,或者輸出一個函數,如map,reduce,sort。

用haskell的函數簽名來表示:

hocFactory:: W: React.component => E: React.component

使用場景

可以用來對組件進行二次加工和抽象,比如:對Input組件進行樣式改動、添加新的props屬性;某些可以復用的邏輯抽象后再注入組件。

所以 HOC 的作用大概有以下幾點:

  • 代碼復用和邏輯抽象
  • 對 state 和 props 進行抽象和操作
  • Render 劫持

如何實現

  • 屬性代理(props proxy):高階組件通過被包裹的React組件來操作props,從而能夠實現控制props、引用refs、抽象state。

1.1 控制props

import React, { Component, Fragment } from 'react';const MyContainer = WrappedComponent =>class extends Component {render() {const newProps = {text: 'newText',};return (<><span>通過 props proxy 封裝HOC</span><WrappedComponent {...this.props} {...newProps} /></>);}};

從這里可以看到,在render中返回來傳入WrappedComponent 的React組件,這樣我們就可以通過HOC在props中傳遞屬性、添加組件及樣式等等。

使用也是非常簡單:

import React, { Component } from 'react'; import MyContainer from './MyContainer.jsx';class App extends Component {... }export default MyContainer(App);

當然也可以使用裝飾器@decorator:”接收一個類作為參數,返回一個新的內部類“,與HOC的定義如出一轍,十分契合。

import React, { Component } from 'react'; import MyContainer from './MyContainer.jsx';@MyContainer class App extends Component {... }export default App;

1.2 通過refs使用引用

import React, { Component } from 'react';const RefsHOC = WrappedComponent =>class extends Component {proc(wrappedComponentInstance) {wrappedComponentInstance.refresh();}render() {const props = Object.assign({}, this.props, { ref: this.proc.bind(this) });return <WrappedComponent {...props} />;}};export default RefsHOC;

render() 時會執行 ref 回調,即proc方法,該方法可以獲取 WrappedComponent 的實例,其中包含組件的 props,方法,context等。我們也可以在 proc 中進行一些操作,如控制組件刷新等。

1.3 抽象state

我們可以通過向 WarppedComponent 提供 props 和 回調函數抽象state,將原組件抽象成展示型組件,隔離內部state。

import React, { Component } from 'react';const MyContainer = WrappedComponent =>class extends Component {constructor(props) {super(props);this.state = {name: '',};}onHandleChange = e => {const val = e.target.value;this.setState({name: val,});};render() {const newProps = {name: {value: this.state.name,onChange: this.onHandleChange,},};return <WrappedComponent {...this.props} {...newProps} />;}};

我們將 input 組件中 name props 的 onChange方法提取到了高階組件中,這樣就有效的抽象了同樣的state操作。

import React, { Component } from 'react'; import MyContainer from './MyContainer.jsx';@MyContainer class MyInput extends Component {render() {return <input type="text" {...this.props.name} />;} }export default MyInput;

參考鏈接

深入React技術棧?book.douban.comJavascript 中的裝飾器?aotu.io

總結

以上是生活随笔為你收集整理的react 给一个引用的组件添加新属性_高阶组件在React中的应用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。