class Child extends Component {
render() {
const {left,center,right} = this.props
return (
<div className='ccc'>
<div className='left'>
{left}
</div>
<div className='center'>
{center}
</div>
<div className='right'>
{right}
</div>
</div>
)
}
}
上面是子组件
export default class App extends Component {
render() {
return (
<div>
<Child
left={<span>left</span>}
center={<span>center</span>}
right={<span>right</span>}
/>
</div>
)
}
}
上面是父组件 通过 props传值来解决插槽的功能
最顶级组件 App
//作为默认值显示
const context = React.createContext({
name:'张角',
age:23
})
export default class App extends Component {
state = {
name:'孙策3',
age:17
}
render() {
const {name,age} = this.state
return (
<div>
<context.Provider value={this.state}>
<A />
</context.Provider>
</div>
)
}
}
中间级组件
class A extends Component {
render() {
return (
<div>
<B/>
</div>
)
}
}
孙级组件
class B extends React.Component{
render(){
console.log(this.context,'这个是b打印出来的')
return(
<div>{this.context.name}
<div>{this.context.age}</div>
</div>
)
}
}
B.contextType = context
///
//另外一种写法不用写contextType = context
class B extends React.Component{
render(){
return(
<div>
<context.Consumer>
{
value => {
console.log(value)
return (
<div>
{value.name}
{value.age}
</div>
)
}
}
</context.Consumer>
</div>
)
}
}