2-跨组件通信-context-类组件

2-跨组件通信-context-类组件

 

 

import React, { Component } from ‘react‘
 
const userContext = React.createContext({
    nickname:‘AAA‘,
    level:0
}) 
class ProfileHeader extends Component{
    render(){
        console.log(this.context);
        return ( 
            <div>
                <h2>用户昵称: {this.context.nickname}</h2>
                <h2>用户等级: {this.context.level}</h2>
            </div>
        )
    } 
}
ProfileHeader.contextType = userContext;

function Profile(){
    return (
        <div> 
            <ProfileHeader />
            <ul>
                <li>设置1</li>
                <li>设置2</li>
                <li>设置3</li>
            </ul>
        </div>
    )
}
export default class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            nickname:‘Eric‘,
            level:99
        }
    }
    render() { 
        return (
            <div> 
                <userContext.Provider value={this.state}>
                  <Profile />
                </userContext.Provider> 
            </div>
        )
    }
}

2-跨组件通信-context-类组件

上一篇:Redis 几个容易弄混的概念


下一篇:Winform的学习