context
const {Provider, Consumer} = React.createContext(defaultValue);
1.Provider:接收一个将要被往下层层传递的props,该值需在组件树最顶层设置。一个Provider可以关联到多个Consumers。通常是父组件
2.Consumer:接收一个函数作为子节点,函数接收当前 context 的值,即Provider提供的props值或创建时的默认值并返回到一个dom节点。传递给函数的props值等于组件树中最接近自身的Provider的props值。
一、定义一个theme.js文件作为context组件
import React from 'react';
export const ThemeContext = React.createContext({
background: 'red',
color: 'white'
});
一、顶层组件
//context=====Raact跨组件传递数据
//使用Context,可以跨越组件进行数据传递。
//跨组件传递样式
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跨组件传递数据的中间层组件
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>
)
}
}