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

问题描述 投票:0回答:2

我是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>

我想在点击开关时更改整个应用主题。 (抱歉英文不好)

reactjs
2个回答
0
投票

你能试试吗

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

由于此处的代码在this.state.checked上运行为true或false。您当前的代码将设置要检查的状态:选中而不是选中:true。

如果这没有帮助,请在Web浏览器中使用React dev工具查看正在执行的状态。

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

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>
© www.soinside.com 2019 - 2024. All rights reserved.