【问题标题】:Changing React Theme Context on button click单击按钮时更改 React 主题上下文
【发布时间】:2020-05-31 06:11:33
【问题描述】:

Main.js

import React from "react"
//import PropTypes from "prop-types"
import ThemeContext from "./ThemeContext"

function Button(props) {
    return (
        <ThemeContext.Consumer>
            {theme => (
                <button className={`${theme}-theme`}>Switch Theme</button>
            )}
        </ThemeContext.Consumer>
    )    
}

export default Button

index.js

import ReactDOM from 'react-dom';
import App from './App';
import ThemeContext from "./ThemeContext"



ReactDOM.render(
    <ThemeContext.Provider value={"dark"}>
       <App /> 
    </ThemeContext.Provider>, 
    document.getElementById('root'));

大家好,我正在尝试将上下文与 React 结合使用。我有上面的代码,我正在尝试将主题从浅色变为深色。 现在,如果我将“暗”更改为“亮”,我可以手动更改页面的主题,但我只想通过单击按钮来做到这一点。今天尝试开始工作非常令人沮丧,我在谷歌上搜索了很多,但我发现的一切都比较复杂,我想我无法理解。任何帮助,将不胜感激。谢谢

【问题讨论】:

    标签: javascript reactjs api components


    【解决方案1】:

    传递一个回调来更改主题以及上下文中的主题数据怎么样?比如:

    // Wraps the previous theme provider render
    class Root extends Component {
      // Store theme in state
      state = {
        theme: "dark"
      };
    
      // Callback to change it
      changeTheme = newTheme => {
        this.setState({ theme: newTheme });
      };
    
      render() {
        const { theme } = this.state;
        // Here pass down an object instead of a string with both the theme string and the callback
        return (
          <ThemeContext.Provider value={{ theme: theme, changeTheme: this.changeTheme }}>
            <App />
          </ThemeContext.Provider>
        );
      }
    }
    
    function Button(props) {
      return (
        // your consumer now gets both the theme and the callback
        <ThemeContext.Consumer>
          {({ theme, changeTheme }) => (
            <button
              onClick={() => changeTheme(theme === "dark" ? "light" : "dark")}
              className={`${theme}-theme`}
            >
              Switch Theme
            </button>
          )}
        </ThemeContext.Consumer>
      );
    }
    
    // Finally just render the root
    ReactDOM.render(<Root />, document.getElementById("root"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 2021-10-06
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多