如何将状态数据传递到其他组件

时间:2019-03-23 07:53:08

标签: reactjs

我是React的新手。这是问题所在。 当我更改开关状态时,我想更改整个应用程序的主题。

这是我在侧边栏上的开关组件

constructor() {
    super();
    this.state = { checked: false };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(checked) {
    this.setState({ checked });
    console.log('ddd');
  }
  render() {
    return (
      <Switch
        checked={this.state.checked}
        onChange={this.handleChange}
        onColor='#86d3ff'
        onHandleColor='#0061ac'
        handleDiameter={20}
        uncheckedIcon={false}
        checkedIcon={false}
        boxShadow='0px 1px 5px rgba(0, 0, 0, 0.6)'
        activeBoxShadow='0px 0px 1px 10px rgba(0, 0, 0, 0.2)'
        height={10}
        width={30}
        className='react-switch'
        id={this.props.id}
      />
    );
  }

这是ThemeProvider包含的路由组件

<ThemeProvider theme={{ mode: this.state.checked ? 'dark' : 'light' }}>
        ...
      </ThemeProvider>

我想在单击开关时更改整个应用程序主题。 (对不起,英语不好)

2 个答案:

答案 0 :(得分:0)

可以请您尝试

 handleChange(checked) {
    this.setState({ checked: true });
    console.log('ddd');
  }

由于此处的代码在this.state.check上运行,所以检查是对还是对。您当前的代码将设置状态为check:checked而不是checked:true。

如果这样做没有帮助,请在Web浏览器中使用React开发工具来查看状态。

<ThemeProvider theme={{ mode: this.state.checked ? 'dark' : 'light' }}>
        ...
      </ThemeProvider>

答案 1 :(得分:0)

您可以将组件状态值放入redux存储中(或使用mobx或作出反应Context),其他组件可以使用它。

// switch component
handleChange(checked) {
  this.props.appActions.setAppTheme({ checked }); // this action will set the value to redux store, you should implement the action and reducer method by yourself
}

// other component
<ThemeProvider theme={{ mode: this.props.appState.checked ? 'dark' : 'light' }}>
  // other component connect to the redux store so it can get the state value
</ThemeProvider>
相关问题