React中的新特性之Context
-
定义:Context提供了一种方式,能够让数据在组件树中传递而不必一级一级动手传递
-
结构:Provider提供数据,Consumer去使用数据
-
简单使用Context
<!-- 通过createContext创建Context实例对象 -->
import React, { Component, createContext } from 'react';
// createContext(defaultValue)创建一个Context实例对象
// defaultValue放的是默认值
// 当Consumer找不到与之匹配的Provider,不会报错,会显示默认值
const BatteryContext = createContext(30);
const OnlineContext = createContext();
class Mini extends Component {
render() {
return (
// BatteryContext.Consumer中写的是一个函数
/* <BatteryContext.Consumer>
{
battery => <h1>Battery:{battery}</h1>
}
</BatteryContext.Consumer> */
// 嵌套两个context
<BatteryContext.Consumer>
{
battery=>(
<OnlineContext.Consumer>
{online=><h1>Battery:{battery},Online:{String(online)}</h1>}
</OnlineContext.Consumer>
)
}
</BatteryContext.Consumer>
)
}
}
class Middle extends Component {
render() {
return <Mini></Mini>
}
}
class App extends Component {
state = {
battery: 60,
online:false
}
render() {
const { battery,online } = this.state;
return (
// context必须要有值
<BatteryContext.Provider value={battery}>
<OnlineContext.Provider value={online}>
<button
type="button"
onClick={() => this.setState({ battery: battery - 1 })}>
press
</button>
<button
type="button"
onClick={() => this.setState({ online: !online })}>
switch
</button>
<Middle></Middle>
</OnlineContext.Provider>
</BatteryContext.Provider>
)
}
}
export default App;
点击press,Battery的值就减少1,点击switch,online的值取反
注意:如果只有一个Context,使用contextType会更加简单方便,把上面Mini组件修改一下就行
class Mini extends Component {
// 如果只是一个Context,可以使用contextType,代码比较简单
static contextType=BatteryContext;
render() {
const battery= this.context;
return (
// BatteryContext.Consumer中写的是一个函数
/* <BatteryContext.Consumer>
{
battery => <h1>Battery:{battery}</h1>
}
</BatteryContext.Consumer> */
// 使用contextType
<h1>Battery:{battery}</h1>
)
}
}