react-context
宁静致远 7/19/2020 react
# context(上下文)
Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。
- 公共语言、主题 传给每个子组件
- 用props 层层传递太繁琐
- 用redux 小题大做
React.createContext:创建一个上下文的容器(组件), defaultValue可以设置共享的默认数据
const {Provider, Consumer} = React.createContext(defaultValue);
1
Provider(生产者): 和他的名字一样。用于生产共享数据的地方。生产什么呢? 那就看value定义的是什么了。value:放置共享的数据。
<Provider value={/*共享的数据*/}>
/*里面可以渲染对应的内容*/
</Provider>
1
2
3
2
3
Consumer(消费者):这个可以理解为消费者。 他是专门消费供应商(Provider 上面提到的)产生数据。Consumer需要嵌套在生产者下面。才能通过回调的方式拿到共享的数据源。当然也可以单独使用,那就只能消费到上文提到的defaultValue
<Consumer>
{value => /*根据上下文 进行渲染相应内容*/}
</Consumer>
1
2
3
2
3
parent
import React, { Component } from 'react';
import Son from './Son'
export const { Provider, Consumer } = React.createContext('light')
class ParentComponent extends Component {
constructor(){
super()
this.state = {
themeName: 'light'
}
}
handleClick = () => {
this.setState({
themeName: this.state.themeName === 'light' ? 'dark' : 'light'
})
}
render(){
return <Provider value={this.state.themeName}>
父组件定义的值: {this.state.themeName} <button onClick={this.handleClick}>更新</button>
<hr />
<Son></Son>
</Provider>
}
}
export const Parent = ParentComponent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
son
import React, { Component } from 'react'
import Grandson from './Grandson'
import { Consumer } from './Parent'
class Son extends Component {
render(){
return <Consumer>
{
(themeName) => {
return (
<>
son接收父组件的上下文传递下来的值 {themeName}
<hr />
<Grandson></Grandson>
</>
)
}
}
</Consumer>
}
}
export default Son
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
son
import React from 'react'
import { Consumer } from './Parent'
const Grandson = () => {
return <Consumer>
{
(themeName) => {
return (
<h1>grandson 接收来自 parent 上下文的传值 {themeName}</h1>
)
}
}
</Consumer>
}
export default Grandson
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18