欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

React?Context詳解使用方法

 更新時(shí)間:2022年12月03日 11:36:10   作者:碼農(nóng)小菲  
Context提供了一個(gè)無(wú)需為每層組件手動(dòng)添加props,就能在組件樹(shù)間進(jìn)行數(shù)據(jù)傳遞的方法。在一個(gè)典型的?React?應(yīng)用中,數(shù)據(jù)是通過(guò)props屬性自上而下(由父及子)進(jìn)行傳遞的,但這種做法對(duì)于某些類(lèi)型的屬性而言是極其繁瑣的

一、概述

  • Context 提供了一個(gè)無(wú)需為每層組件手動(dòng)添加 props,就能在組件樹(shù)間進(jìn)行數(shù)據(jù)傳遞的方法。
  • 如果多個(gè)組件中都需要這個(gè)值 或者 獲取值和使用值的層級(jí)相隔很遠(yuǎn),就可以使用Context(上下文)來(lái)共享數(shù)據(jù)。
  • 如:地區(qū)偏好,UI 主題、當(dāng)前認(rèn)證的用戶、語(yǔ)言等
  • 謹(jǐn)慎使用,這會(huì)使組件的復(fù)用性變差

二、API

React.createContext

const MyContext = React.createContext(defaultValue)
  • 創(chuàng)建一個(gè) Context 對(duì)象
  • 提供一個(gè)默認(rèn)值,只有當(dāng)組件所處的樹(shù)中沒(méi)有匹配到 Provider 時(shí),其 defaultValue 參數(shù)才會(huì)生效

Context.Provider

  const MyContext = React.createContext(defaultValue)
  <MyContext.Provider value={xxx}> ... </MyContext.Provider>
  • 每個(gè) Context 對(duì)象都會(huì)返回一個(gè) Provider React 組件
  • Provider 接收一個(gè) value 屬性,傳遞給消費(fèi)組件。一個(gè) Provider 可以對(duì)應(yīng)多個(gè)消費(fèi)組件。多個(gè) Provider 也可以嵌套使用,里層的會(huì)覆蓋外層的數(shù)據(jù)
  • value 值發(fā)生變化時(shí),它內(nèi)部的所有消費(fèi)組件都會(huì)重新渲染

Class.contextType

class MyClass extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* 在組件掛載完成后,使用 MyContext 組件的值來(lái)執(zhí)行一些有副作用的操作 */
  }
  componentDidUpdate() {
    let value = this.context;
    /* ... */
  }
  componentWillUnmount() {
    let value = this.context;
    /* ... */
  }
  render() {
    let value = this.context;
    /* 基于 MyContext 組件的值進(jìn)行渲染 */
  }
}
MyClass.contextType = MyContext;
  • 掛載在 class 上的 contextType 屬性會(huì)被重賦值為一個(gè)由 React.createContext() 創(chuàng)建的 Context 對(duì)象
  • 可以在任意生命周期中訪問(wèn)

Context.Consumer

<MyContext.Consumer>
   {value => /* 基于 context 值進(jìn)行渲染*/}
</MyContext.Consumer>
  • 消費(fèi)組件(子組件)中使用value
  • 函數(shù)作為子元素;這個(gè)函數(shù)接收當(dāng)前的 context 值,返回一個(gè) React 節(jié)點(diǎn)。傳遞給函數(shù)的 value 值等同于往上組件樹(shù)離這個(gè) context 最近的 Provider 提供的 value 值。如果沒(méi)有對(duì)應(yīng)的 Provider,value 參數(shù)等同于傳遞給 createContext() 的 defaultValue。

Context.displayName

const MyContext = React.createContext()
MyContext.displayName = 'MyDisplayName'
<MyContext.Provider> //在 DevTools 中顯示的標(biāo)簽:MyDisplayName.Provider  
<MyContext.Consumer>//在 DevTools 中顯示的標(biāo)簽:MyDisplayName.Consumer  
//如果沒(méi)有 MyContext.displayName = 'MyDisplayName' ,則顯示Context.Provider、Context.Consumer

在 DevTools 中需要顯示的內(nèi)容

三、使用

1.自定義Context (類(lèi)組件中使用)

//ThemeContext.js
import React from 'react'
export const ThemeContext = React.createContext('light')
//themed-button.js
//在需要的位置使用 Class.contextType
import React, { Component } from 'react';
import ThemeContext from "./context/ThemeContext.js";

class ThemedButton extends Component {
	static contextType = ThemeContext;
	render() {
		return <button>{this.context}</button>;
	}
}
export default ThemedButton
//app.js
//上下文包裹組件 Context.Provider
import ThemeContext from './context/ThemeContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
function App() {
  return (
    <ThemeContext.Provider value='dark'> //dark將默認(rèn)值light覆蓋
      <div className="App">
        <header className="App-header">
          <ThemedButton />
        </header>
      </div>
    </ThemeContext.Provider>
  );
}
export default App;

2.使用Consumer支持獲取多個(gè)Context上的值

需要多個(gè)上下文的值時(shí)可以使用Consumer

//ThemeContext.js
import React from 'react'
const ThemeContext = React.createContext('light')
ThemeContext.displayName = 'ThemeContext'
export default ThemeContext
//UserContext.js
import React from 'react'
const UserContext = React.createContext('guest')
UserContext.displayName = 'UserContext'
export default UserContext
//app.js
//使用Provider賦值:
import React, { Component } from 'react';
import ThemeContext from './context/ThemeContext.js';
import UserContext from './context/UserContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
class App extends Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
        <ThemeContext.Provider value={'dark'}>
          <div className="App">
            <UserContext.Provider value={'user'}>
              <header className="App-header">
                <ThemedButton />
              </header>
            </UserContext.Provider>
          </div>
        </ThemeContext.Provider>
    );
  }
}
export default App
//themed-button.js
import React, { Component } from 'react';
import ThemeContext from "./context/ThemeContext.js";
import UserContext from "./context/UserContext.js";
class ThemedButton extends Component {
	render() {
		return (
			<>
				<ThemeContext.Consumer>
					{theme => <div>{theme}</div>}
				</ThemeContext.Consumer>
				<UserContext.Consumer>
					{user => <div>{user}</div>}
				</UserContext.Consumer>
			</>
		);
	}
}
export default ThemedButton

3.useContext使用(函數(shù)式組件中使用)

react原生Hook ,讓函數(shù)式組件也可以使用Context,而且支持多個(gè)不同類(lèi)型的context

//ThemeContext.js
import React from 'react'
const ThemeContext = React.createContext('light')
ThemeContext.displayName = 'ThemeContext'
export default ThemeContext
//UserContext.js
import React from 'react'
const UserContext = React.createContext('guest')
UserContext.displayName = 'UserContext'
export default UserContext
//app.js
//使用Provider賦值:
import React, { Component } from 'react';
import ThemeContext from './context/ThemeContext.js';
import UserContext from './context/UserContext.js';
import ThemedButton from './ThemedButton.js';
import './App.css';
const App = () => {
  render() {
    return (
        <ThemeContext.Provider value={'dark'}>
          <div className="App">
            <UserContext.Provider value={'user'}>
              <header className="App-header">
                <ThemedButton />
              </header>
            </UserContext.Provider>
          </div>
        </ThemeContext.Provider>
    );
  }
}
export default App
//themed-button.js
import { useContext } from 'react'
import ThemeContext  from './context/ThemeContext'
import UserContext from './context/UserContext'
const ThemedButton = () => {
 const theme = useContext(ThemeContext)
 const user = useContext(UserContext)
 return (
    <>
		<div>{theme}</div>
		<div>{user}</div>
	</>
 )
}
export default ThemedButton

到此這篇關(guān)于React Context詳解使用方法的文章就介紹到這了,更多相關(guān)React Context內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • React實(shí)現(xiàn)組件全屏化的操作方法

    React實(shí)現(xiàn)組件全屏化的操作方法

    開(kāi)發(fā)今天給我提了一個(gè)sql編輯器輸入框比較小,不支持放大,不太方便,下面看下我的處理方法,本文基于React+antd,給大家演示一個(gè)完整的全屏demo,感興趣的朋友一起看看吧
    2021-10-10
  • react component changing uncontrolled input報(bào)錯(cuò)解決

    react component changing uncontrolled in

    這篇文章主要為大家介紹了react component changing uncontrolled input報(bào)錯(cuò)解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-12-12
  • 一文詳解React?Redux使用方法

    一文詳解React?Redux使用方法

    這篇文章主要介紹了一文詳解React?Redux使用方法,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容戒殺,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • react?Table準(zhǔn)備Spin?Empty?ConfigProvider組件實(shí)現(xiàn)

    react?Table準(zhǔn)備Spin?Empty?ConfigProvider組件實(shí)現(xiàn)

    這篇文章主要為大家介紹了react?Table準(zhǔn)備Spin、Empty、ConfigProvider組件實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪<BR>
    2023-02-02
  • 如何去除富文本中的html標(biāo)簽及vue、react、微信小程序中的過(guò)濾器

    如何去除富文本中的html標(biāo)簽及vue、react、微信小程序中的過(guò)濾器

    這篇文章主要介紹了如何去除富文本中的html標(biāo)簽及vue、react、微信小程序中的過(guò)濾器,在vue及react中經(jīng)常會(huì)遇到,今天通過(guò)實(shí)例代碼給大家講解,需要的朋友可以參考下
    2018-11-11
  • antd-react使用Select組件defaultValue踩的坑及解決

    antd-react使用Select組件defaultValue踩的坑及解決

    這篇文章主要介紹了antd-react使用Select組件defaultValue踩的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • react?中?mobx的使用案例詳解

    react?中?mobx的使用案例詳解

    這篇文章主要介紹了react?中?mobx的使用案例詳解,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-04-04
  • React 狀態(tài)的不變性實(shí)例詳解

    React 狀態(tài)的不變性實(shí)例詳解

    這篇文章主要為大家介紹了React 狀態(tài)的不變性實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-11-11
  • react-router-dom v6版本實(shí)現(xiàn)Tabs路由緩存切換功能

    react-router-dom v6版本實(shí)現(xiàn)Tabs路由緩存切換功能

    今天有人問(wèn)我怎么實(shí)現(xiàn)React-Router-dom類(lèi)似標(biāo)簽頁(yè)緩存,很久以前用的是react-router v5那個(gè)比較容易實(shí)現(xiàn),v6變化挺大,但了解react的機(jī)制和react-router的機(jī)制就容易了,本文介紹react-router-dom v6版本實(shí)現(xiàn)Tabs路由緩存切換,感興趣的朋友一起看看吧
    2023-10-10
  • React中的函數(shù)式插槽詳解

    React中的函數(shù)式插槽詳解

    這篇文章主要為大家詳細(xì)介紹了React?開(kāi)發(fā)中遇到的具名插槽的函數(shù)用法,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,有興趣的小伙伴可以了解一下
    2023-11-11

最新評(píng)論