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

學無先后,達者為師

網站首頁 編程語言 正文

react.createContext

作者:愛上布洛格的鴨鴨 更新時間: 2022-07-17 編程語言

1. 隔代組件傳值

1.1 props傳遞

傳遞方式:通過props屬性自上而下逐層傳遞
存在問題:層級過多導致傳值繁瑣

import React from 'react'

//父組件
class App extends React.Component{
  render(){
    return (
      //1.傳遞value值
      <Demo1 value="hello hello"/>
    )
  }
}
//中間組件
class Demo1 extends React.Component{
  render(){
    return (
      //2.中間組件幫助傳遞value值
      <Demo2 value={this.props.value} />
    )
  }
}
//子組件
class Demo2 extends React.Component{
  render(){
    return (
      //3.接收value值
      <h1>{this.props.value}</h1>
    )
  }
}

export default App

1.2 Context傳遞

傳遞方式:類似于全局變量
存在問題:組件復用性較差
使用方法:

  1. 創建Context(ValueContext可任意命名)
    const ValueContext = React.createContext('') //默認值為''
  2. 用ValueContext.Provider包裹組件樹中的根節點,并傳遞value
    <ValueContext.Provider value="hello hello">
  3. 此時,該組件樹中的節點均能訪問到步驟2中根節點所傳遞的value
    3.1 指定contextType讀取當前的ValueContext
    static contextType = ValueContext
    3.2 讀取value值
    this.context
import React from 'react'

//1.創建一個Context
const ValueContext = React.createContext('') //默認值為''
//父組件
class App extends React.Component{
  render(){
    return (
      //2.用ValueContext.Provider包裹組件樹中的根節點
      //傳遞value值為"hello hello"
      //組件樹中的節點均能訪問到該value值
      <ValueContext.Provider value="hello hello">
        <Demo1/>
      </ValueContext.Provider>
    )
  }
}
//中間組件
class Demo1 extends React.Component{
  //指定contextType讀取當前的ValueContext
  static contextType = ValueContext
  render(){
    return (
      //this.context即父組件中傳遞的"hello hello"
      <div>
        <h1>{this.context}</h1>
        <Demo2/>
      </div>
    )
  }
}
//子組件
class Demo2 extends React.Component{
  //指定contextType讀取當前的ValueContext
  static contextType = ValueContext
  render(){
    return (
      //this.context即父組件中傳遞的"hello hello"
      <h2>{this.context}</h2>
    )
  }
}

export default App

效果圖:
在這里插入圖片描述

原文鏈接:https://blog.csdn.net/SmallPig_Code/article/details/125708042

欄目分類
最近更新