React Context(一):隱式傳遞數據
阿新 • • 發佈:2019-01-26
urn let png pan import fun .get port exp
一 Context概述
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
二 項目結構
三 代碼
1 theme-context.js
import React from ‘react‘; // 主題數據 export const themes = { gray: { background: ‘gray‘, }, gold: { background:‘gold‘, }, }; // 創建上下文對象,參數將作為上下文對象的默認值 export const ThemeContext = React.createContext( themes.gray // default value );
2 themed-button.js
import React from ‘react‘; import { ThemeContext } from ‘./theme-context‘; class ThemedButton extends React.Component { render() { let props= this.props; let theme = this.context; return ( <button {...props} style={{...theme}} /> ) } } // 給ThemedButton類綁定上下文對象:ThemedButton類的對象的context屬性,等於上下文對象的默認值。 ThemedButton.contextType = ThemeContext; export default ThemedButton;
3 app.js
import React, { Fragment } from ‘react‘; import { ThemeContext, themes } from ‘./theme-context‘; import ThemedButton from ‘./themed-button‘; // An intermediate component that uses the ThemedButton // 工具欄組件(中間件) function Toolbar(props) { return ( <ThemedButton onClick={props.changeTheme}> 改變上下文對象 </ThemedButton> ); } class App extends React.Component { constructor(props) { super(props); this.state = { theme: themes.gray }; this.toggleTheme = () => { this.setState(state => ({ theme: state.theme === themes.gray ? themes.gold : themes.gray })); } } render() { return ( <Fragment> {/* 在Provider中,使用Provider提供的值 */} <ThemeContext.Provider value={this.state.theme}> <Toolbar changeTheme={this.toggleTheme} /> </ThemeContext.Provider> {/* 不在Provider中,使用上下文對象的默認值 */} <section> <ThemedButton /> </section> </Fragment> ); } } export default App;
4 index.js
import React from ‘react‘; import ReactDOM from ‘react-dom‘; import App from ‘./App‘; ReactDOM.render(<App />, document.getElementById(‘root‘));
四 運行效果
1 初始化
2 點擊按鈕
React Context(一):隱式傳遞數據