【问题标题】:passing a paremeter in a consumer to change context value在消费者中传递参数以更改上下文值
【发布时间】: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


    【解决方案1】:

    你能不能把下面两个部分替换并检查一次。

    ----------------------------- 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
            })
          } 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2019-07-27
      • 1970-01-01
      • 2022-08-08
      相关资源
      最近更新 更多