我们在class组件中使用context时,一定会使用c.Consumer,我们在Consumer中,需要写一个函数,
<context.Consumer>
{
(item) => {
return <div>{item}</div>
}
}
</context.Consumer>
上面在的这种写法第一眼看上去很奇怪。其实,consumer内部是类似下面的一个结构
class Consumer extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{this.props.children()}
</div>
)
}
}
consumer其实是通过了this.props.children获取了组件内部的函数的返回值,并对其进行渲染。