【发布时间】:2019-10-16 03:40:59
【问题描述】:
这几天我遇到了很大的困难。如何在提供者包装器内的嵌套组件中更改上下文值。
例如:
提供者:
<MapThemeContext.Provider value={this.state}>
<div className="App">
<Dashboard/>
</div>
</MapThemeContext.Provider>
this.state 的位置(在与提供者呈现位置相同的组件内)
this.state = {
theme : themes.silver,
handleMapChange: this.handleMapChange,
}
this.handleMapChange = (style) => {
if (style == "silver") {
this.setState({
theme : themes.silver
});
} else if (style == "dark") {
this.setState({
theme : themes.dark
})
}
}
}
在提供者的深处(嵌套在Dashboard 内)是一个消费者:
<MapThemeContext.Consumer>
{({handleMapChange}) => (
<div>
<Button variant="contained" className={classes.button} onClick={e => handleMapChange('silver')}> // this does not work
Silver
</Button>
<Button variant="contained" className={classes.button} onClick={handleMapChange}>
Dark
</Button>
</div>
)}
</MapThemeContext.Consumer>
消费者内部的方法调用如何使用正确的参数来设置上下文的值?
再次深入人心的是另一个使用此上下文作为主题的组件,它确实正确使用了默认值。我只是不明白如何在消费者按钮上更改它。
上下文内容:
export const themes = {
silver: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
};
export const ThemeContext = React.createContext(
theme: themes.silver,
handleMapChange: () => {},
);
【问题讨论】:
标签: reactjs react-context