classSonextendsReact.Component{
static contextTypes = {
color:PropTypes.string,
setColor:PropTypes.func,
name:PropTypes.name
}
render(){
return (
<><pstyle={{color:this.context.color}}>{this.context.name}</p><buttononClick={()=>{this.context.setColor('red')}}>
Change Color To Red
</button><buttononClick={()=>{this.context.setColor('green')}}>
Change Color To Green
</button></>
)
}
}
复制代码
classSonextendsComponent{
static contextType = ThemeContext;
render(){
return (
<><pstyle={{color:this.context.color}}>{this.context.name}</p><buttononClick={()=>{this.context.setColor('red')}}>
Change Color To Red
</button><buttononClick={()=>{this.context.setColor('green')}}>
Change Color To Green
</button></>
)
}
}
复制代码
functionSon(){
return (
<ThemeContext.Consumer>
{
value=>(
<><pstyle={{color:value.color}}>{value.name}</p><buttononClick={()=>{value.setColor('red')}}>Change Color To Red</button><buttononClick={()=>{value.setColor('green')}}>Change Color To Green</button><GrandSon/></>
)
}
</ThemeContext.Consumer>
)
}
复制代码