在react中,context用于共享數(shù)據(jù),并且允許數(shù)據(jù)隔代傳遞;context提供了一種新的組件之間共享數(shù)據(jù)的方式,不必顯式地通過組件樹的逐層傳遞props,能夠避免使用大量重復(fù)的props來傳遞值。
本教程操作環(huán)境:Windows10系統(tǒng)、react17.0.1版、Dell G3電腦。
react中context的用法是什么
Context提供了一種新的組件之間共享數(shù)據(jù)的方式,允許數(shù)據(jù)隔代傳遞,而不必顯式的通過組件樹逐層傳遞props。
Context 提供了一種在組件之間共享值的方式,而不必顯式地通過組件樹的逐層傳遞 props。如果獲取值和使用值的層級相隔很遠,或者需要使用這個值的組件很多很分散,則可以使用Context來共享數(shù)據(jù),避免使用大量重復(fù)的props來傳遞值。如果只是一個組件需要使用這個值,可以在產(chǎn)生這個值的位置生成這個組件,然后用props層層傳遞到組件實際展示的位置。
基本使用方式
1、自定義Context
import React from 'react'; const ThemeContext = React.createContext('light'); export default ThemeContext;
上面的代碼定義了一個ThemeContext,默認值為'light'。
2、在需要的位置使用Context的Provider
import ThemeContext from './context/ThemeContext.js'; import ThemedButton from './ThemedButton.js'; import './App.css'; function App() { return ( <ThemeContext.Provider value='dark'> <div className="App"> <header className="App-header"> <ThemedButton /> </header> </div> </ThemeContext.Provider> ); } export default App;
在組件的最外層使用了自定義Context的Provider,傳入value覆蓋了默認值,之后子組件讀到的ThemeContext的值就是'dark'而不是默認值'light'。如果Provider有value定義就會使用value的值(即使值是undefined,即未傳入value),只有當Provider未提供時才會使用定義時的默認值。
3、定義contextType,使用獲取到的Context上的值
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;
ThemedButton聲明了contextType是ThemeContext,因此this.context的值就是最近的ThemeContext提供的value,也就是'light'。
效果圖:
推薦學(xué)習(xí):《react視頻教程》