在使用者中传递参数以更改上下文值

时间:2019-10-16 03:40:59

标签: reactjs react-context

几天来,我遇到了很大的困难。如何更改提供程序包装器内嵌套组件中的上下文值。

例如:

提供者:

  <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: () => {},
);

1 个答案:

答案 0 :(得分:0)

您能否替换下面的两个部分并检查一次。

----------------------------- Section 1 -----------------------------
const isTheme = this.state.theme;

let buttonName = "dark";
if(isTheme == "silver"){
    buttonName = "silver";
}

<MapThemeContext.Consumer>
    <div>
        <Button variant="contained" className={classes.button} onClick={handleMapChange}>{buttonName}</Button>
    </div>
</MapThemeContext.Consumer>

----------------------------- Section 2 -----------------------------

this.handleMapChange = () => {
      const style = this.state.theme;
      if (style == "silver") {
        this.setState({
          theme : themes.dark 
        });
      } else if (style == "dark") {
        this.setState({
          theme : themes.silver
        })
      } 
    }
}