React Context 提供和消费多个Context
2 年前
· 来自专栏
React
概述:
在应用中提供多个 Context 对象; 消费多个Context的实现;
实例核心:
提供
// 创建多个Context
const UserInfo = React.createContext(null)
const Role = React.createContext(null)
// ..... 通过嵌套提供
<UserInfo.Provider value={/*数据体 */}>
<Role.Provider value={/*数据体 */}>
{/* ......子组件 */}
</Role.Provider>
</UserInfo.Provider>
// .....
消费:
// ...... 通过嵌套消费
<UserInfo.Consumer>
userInfo => (
<Role.Consumer>
role => (
{/* ......通过 userInfo && role 访问Context */}
</Role.Consumer>
</UserInfo.Consumer>
// ......
实例完全:
const UserInfo = React.createContext(null)
const Role = React.createContext(null)
class Parent extends React.Component {
constructor(props){
super(props)
this.state = {
userInfo: {
name: 'bill'
role: "admin"
render(){
return (
<UserInfo.Provider value={this.state.userInfo}>
<Role.Provider value={this.state.role}>
<Children></Children>
</Role.Provider>
</UserInfo.Provider>
function Children(props){
return (
<UserInfo.Consumer>
userInfo => (
<Role.Consumer>
role => (
<div>{userInfo.name}</div>
<div>{role}</div>
</Role.Consumer>
</UserInfo.Consumer>
function App(){
return (
<Parent/>