react context 与 hook-useContext

351 阅读1分钟

不使用hooks

const ThemeContext = React.createContext('light');

classApp extends React.Component {
    render() {
        return (
            <ThemeContext.Provider value = "dark">
                <Toolbar />
            </ThemeContext.Provider>
        )
    }
}


function Toolbar(props) {
    <div>
        <ThemeButton />
    </div>
}

class ThemeButton extends React.Component {
    static contextType = ThemeContext;
    
    render() {
        return <Button theme={this.context} />
    }
}

使用hooks

function ThemeButton()  {
    const contextType = useContext(ThemeContext);
    
    render() {
        return <Button theme={this.context} />
    }
}