第一种: import React, {Component, createContext, useContext} from 'react' const Context = createContext() function Middle () { return ( <div> middle <Child /> </div> ) } function Child () { const Pro = useContext(Context) console.log(Pro) return ( <div> return <div>child-{Pro.value}</div> </div> ) } class Layout extends Component { state = { flags: 1, value: '666' } render () { console.log(this.state.value); return ( <Context.Provider value={this.state}> <div>layout2</div> <Middle /> </Context.Provider> ) } }
第二种:
import React, {Component, createContext} from 'react'
const context = createContext()
function Middle () {
return (
<div>
middle
<Child />
</div>
)
}
class Child extends Component {
static contextType = context;
render () {
return (
<div>
return <div>child-{this.context.value}</div>
</div>
)
}
}
class Layout extends Component {
state = {
flags: 1,
value: '666'
}
render () {
console.log(this.state.value);
return (
<context.Provider value={this.state}>
<div>layout2</div>
<Middle />
</context.Provider>
)
}
}