import React ,{ Component } from 'react';
//创建Context对象
const MyContext = React.create.Context()
//解构Provider
const { Provider } = MyContext
//Father组件
class Father extends Component{
state:{
user:'我是爸爸',
age:18
}
render(){
const { name, age } = this.state
return(
<div>
我是Father组件
<Provider>
//此处的value属性,名字不可自定义
<Son value={{name, age }}/>
<Provider/>
</div>
)
}
}
export default Father
//Son组件
class Son extends Component{
render(){
return(
<div>
我是Son组件
<Grandson/>
</div>
)
}
}
export default Son
//Grandson组件
class Grandson extends Component{
//声明接受Context
static contextType = MyContext
console.log("this.context.name:",this.context.name)//this.context.name:我是爸爸
console.log("this.context.age:",this.context.age)//this.context.age:18
render(){
return(
<div>
我是Grandson组件
</div>
)
}
}
export default Grandson
//若为函数组件
const { Provider, Consumer } = MyContext
function Grandson(){
return(
<div>
我是Grandson组件
<Consumer>
{value => `${value.name},${value.age}`}
<Consumer/>
</div>
)
}
React多组件传值之context
最新推荐文章于 2023-05-22 18:41:41 发布