为什么想用Context
在不使用Context之前,数据通过props传递,如果层级多,需要层层传递到最终层,数据处理上比较繁琐
import React from 'react';
class Parent extends React.Component{
constructor(props) {
super(props);
this.state = {
num: 0
}
}
addNum = () => {
this.setState({ num: ++this.state.num })
}
render() {
return (
// 传递数据
<div>
<Child value={this.state.num} addNum={this.addNum} />
</div>
)
}
}
function Child(props) {
return (
<div>
// 传递数据
<Button value={props.value} addNum={props.addNum} />
</div>
)
}
function Button(props) {
return (
// 接收数据
<button onClick={props.addNum}>
{props.value}
</button>
)
}
export default Parent
Context
使用Context
可以不用层层传递数据 通过Provider和Consumer去处理数据
父组件通过Provider
提供数据
通过Consumer
向子组件传递数据
import React from 'react';
import Child from './child';
import Button from "./button"
const ParentContext = React.createContext()
const { Provider, Consumer } = TestContext
export { Consumer, ParentContext }
class Parent extends React.Component{
static contextType = ParentContext;
constructor(props) {
super(props)
this.state = {
params: {
name: "am",
password: "123456"
},
dataList: [
{name: "Sony", age: 10},
{name: "Lily", age: 8},
{name: "Tang", age: 9}
]
}
this.btnRef = React.createRef()
}
componentDidMount() {
console.log(this.btnRef.current)
}
render() {
return (
// 通过provider包裹 将value向下传递 value存放想要传递的数据
<Provider value={this.state}>
<Child />
<Button ref={this.btnRef}>Click Me</Button>
</Provider>
)
}
}
export default Parent;
import React from 'react';
import {Consumer} from "./index"
class Child extends React.Component{
constructor(props) {
super(props)
}
componentDidMount() {
}
render() {
return (
// 子组件通过Consumenr包裹
// 用函数的方式获取context
// 调用函数 修改数据都交给父组件
<Consumer>
{(context) => {
console.log(context, "context")
return (
<div className="child">
test
</div>
)
}}
</Consumer>
)
}
}
export default Child;
或者通过hooks的方式 useContext
import React, { useContext } from 'react';
import {ParentContext} from "./index"
function Child (){
const context = useContext(ParentContext)
console.log(context, "context")
return (
<div className="child">
test
</div>
)
}
export default Child;