React中context的用法
# React Context的用法
# 作用
一般用于组件传值
# 使用
1、创建GlobalContext.js
import { createContext } from "react"
export const { Provider, Consumer } = createContext()
1
2
3
2
3
2、用Provider把包裹需要实现传值的组件,需要传的值放在value属性上
例如:包裹整个React APP
main.js
import React from "react"
import ReactDom from "react-dom"
import App from "./App"
import { Provider } from "./GlobalContext"
ReactDom.render(
<Provider value={{name: "zs", age: 18}}><App /></Provider>,
document.getElementById("app")
)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
3、在需要接收值的组件中使用Consumer进行包裹
Consumer内部是一个函数
Consumer.js
import React, { Component } from "react"
import { Consumer } from "GlobalContext"
export default class MyClass extends Component{
render(){
return(
<Consumer>
{
(obj)=>(
<div>
<p>name:{obj.name}</p>
<p>age:{obj.age}</p>
</div>
)
}
</Consumer>
)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
编辑 (opens new window)
上次更新: 2021/07/19, 02:17:53