import React from 'react'
import ReactDOM from "react-dom"
const {Provider,Consumer} = React.createContext()
class ContextDemo extends React.Component {
state={
newContext:'createContext'
}
render() {
const {newContext} = this.state
return (
<Provider value={newContext}>
<div>
<label>childContent</label>
<input type="text" value={newContext} onChange={e=>this.setState({newContext:e.target.value})}/>
</div>
<Son />
</Provider>
)
}
}
class Son extends React.Component{
render(){
return <Consumer>
{
(name)=>
<div style={{border:'1px solid red','60%',margin:'20px auto',textAlign:'center'}}>
<p>子组件获取到的内容:{name}</p>
<Grandson />
</div>
}
</Consumer>
}
}
class Grandson extends React.Component{
render(){
return <Consumer>
{
(name)=>
<div style={{border:'1px solid red','60%',margin:'20px auto',textAlign:'center'}}>
<p>孙子组件获取到的内容:{name}</p>
</div>
}
</Consumer>
}
}
function render(){
ReactDOM.render(
<ContextDemo/>,
document.getElementById('root')
);
}
render();