context
const {Provider, Consumer} = React.createContext(defaultValue);
1.Provider:接收一個(gè)將要被往下層層傳遞的props吮旅,該值需在組件樹最頂層設(shè)置。一個(gè)Provider可以關(guān)聯(lián)到多個(gè)Consumers被廓。通常是父組件
2.Consumer:接收一個(gè)函數(shù)作為子節(jié)點(diǎn)党觅,函數(shù)接收當(dāng)前 context 的值,即Provider提供的props值或創(chuàng)建時(shí)的默認(rèn)值并返回到一個(gè)dom節(jié)點(diǎn)倚喂。傳遞給函數(shù)的props值等于組件樹中最接近自身的Provider的props值每篷。
一、定義一個(gè)theme.js文件作為context組件
import React from 'react';
export const ThemeContext = React.createContext({
background: 'red',
color: 'white'
});
一、頂層組件
//context=====Raact跨組件傳遞數(shù)據(jù)
//使用Context焦读,可以跨越組件進(jìn)行數(shù)據(jù)傳遞子库。
//跨組件傳遞樣式
import React from 'react';
import Home from "./views/home/home"
import { ThemeContext } from "./theme"
export default class App extends React.Component {
constructor() {
super()
this.state = {
background: "green",
color: "black"
}
}
render() {
return (
<ThemeContext.Provider value={this.state}>
<Home />
</ThemeContext.Provider>
)
}
}
二、中間層組件
// react跨組件傳遞數(shù)據(jù)的中間層組件
import React from 'react';
import About from "../about/about"
export default class Home extends React.Component {
render() {
return (
<div>
<h1>Home頁面</h1>
<About> have fun </About>
</div>
)
}
}
三矗晃、底層組件
import React from 'react';
import { ThemeContext } from "../../theme"
export default class About extends React.Component {
render() {
return (
<div>
<h1>About頁面</h1>
<ThemeContext.Consumer >
{context => (
<h1 style={{ background: context.background, color: context.color }}>
{this.props.children}
</h1>
)}
</ThemeContext.Consumer>
</div>
)
}
}