在react中,context用于共享數(shù)據(jù),并且允許數(shù)據(jù)隔代傳遞;context提供了一種新的組件之間共享數(shù)據(jù)的方式,不必顯式地通過(guò)組件樹(shù)的逐層傳遞props,能夠避免使用大量重復(fù)的props來(lái)傳遞值。
本教程操作環(huán)境:Windows10系統(tǒng)、react17.0.1版、Dell G3電腦。
react中context的用法是什么
Context提供了一種新的組件之間共享數(shù)據(jù)的方式,允許數(shù)據(jù)隔代傳遞,而不必顯式的通過(guò)組件樹(shù)逐層傳遞props。
Context 提供了一種在組件之間共享值的方式,而不必顯式地通過(guò)組件樹(shù)的逐層傳遞 props。如果獲取值和使用值的層級(jí)相隔很遠(yuǎn),或者需要使用這個(gè)值的組件很多很分散,則可以使用Context來(lái)共享數(shù)據(jù),避免使用大量重復(fù)的props來(lái)傳遞值。如果只是一個(gè)組件需要使用這個(gè)值,可以在產(chǎn)生這個(gè)值的位置生成這個(gè)組件,然后用props層層傳遞到組件實(shí)際展示的位置。
基本使用方式
1、自定義Context
import React from 'react'; const ThemeContext = React.createContext('light'); export default ThemeContext;
上面的代碼定義了一個(gè)ThemeContext,默認(rèn)值為'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覆蓋了默認(rèn)值,之后子組件讀到的ThemeContext的值就是'dark'而不是默認(rèn)值'light'。如果Provider有value定義就會(huì)使用value的值(即使值是undefined,即未傳入value),只有當(dāng)Provider未提供時(shí)才會(huì)使用定義時(shí)的默認(rèn)值。
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視頻教程》