Изменение контекста React Theme при нажатии кнопки - PullRequest
0 голосов
/ 16 февраля 2020

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. У меня есть код выше, что я пытаюсь сделать базовое c изменение темы от светлого к темному. Прямо сейчас я могу вручную изменить тему моей страницы, если я изменю «темный» на «светлый», но я просто хочу сделать это, нажав кнопку. Сегодня было очень сложно пытаться приступить к работе, и я много гуглил, но все, что я нашел, было немного сложнее, и я думаю, что я не смог понять. Любая помощь будет оценена. Спасибо

1 Ответ

0 голосов
/ 16 февраля 2020

Как насчет передачи обратного вызова для изменения темы вместе с данными вашей темы в контексте? Что-то вроде:

// 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"));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...