【发布时间】:2021-11-26 22:30:19
【问题描述】:
我在 useContext 的帮助下将变量名称 theme 传递给反应中的每个组件。我想根据以下情况更改 body or root element 的 bgColor,因为我的主题会发生变化。只是如果
- 主题 === 灯光:bgColor => 白色
- 主题 === 深色:bgColor => #2d2d2d
- 主题 === 深暗:bgColor => 黑色
如何在任何 React 组件中访问 root/body 元素的 CSS 属性,反之亦然(如何访问 `App.css 中变量 theme 的值)?两种方法中的任何一种都适合我。
我在我的一个 React 组件中更改主题如下?
import { useContext } from "react";
import Notes from "./Notes";
import themeContext from "../context/themes/themeContext";
const Home = (props) => {
const contextForThemes = useContext(themeContext);
const { theme } = contextForThemes;
let noteStyle = {
backgroundColor: "white",
color: "black",
};
if (theme.light) {
noteStyle = { backgroundColor: "white", color: "black" };
} else if (theme.dark) {
noteStyle = {
backgroundColor: "#2d2d2d",
color: "whitesmoke",
};
} else if (theme.anotherDark) {
noteStyle = {
backgroundColor: "black",
color: "#84ff00",
};
}
return (
<div style={noteStyle}>
<Notes showAlert={props.showAlert} />
</div>
);
};
export default Home;
【问题讨论】:
标签: javascript html css reactjs react-hooks