我正在尝试有史以来最简单的主题切换,以响应上下文,并且似乎无法在上下文更改时重新渲染图标。其他所有内容都可以正常工作:颜色,背景图像...它会根据初始状态呈现任何一个图标,但是当切换主题时图标不会更新。
import React, { useContext } from "react"
import { ThemeContext } from "../../contexts/ThemeContext"
const ThemeToggle = () => {
const { isDarkMode, dark, light, toggleTheme } = useContext(ThemeContext)
const theme = isDarkMode ? dark : light
return (
<li
style={{ background: theme.bgPrimary, color: theme.text }}
onClick={toggleTheme}
>
<i className={theme.ico} />
</li>
)
}
export default ThemeToggle
上下文:
import React, { Component, createContext } from "react"
export const ThemeContext = createContext()
class ThemeContexProvider extends Component {
state = {
isDarkMode: false,
light: {
text: "#333",
bgPrimary: "#eee",
bgSecondary: "#333",
ico: "fas fa-moon"
},
dark: {
text: "#ddd",
bgPrimary: "#000003",
bgSecondary: "#bbb",
ico: "fas fa-sun"
}
}
toggleTheme = () => {
this.setState({ isDarkMode: !this.state.isDarkMode })
}
render() {
return (
<ThemeContext.Provider
value={{ ...this.state, toggleTheme: this.toggleTheme }}
>
{this.props.children}
</ThemeContext.Provider>
)
}
}
export default ThemeContexProvider
答案 0 :(得分:0)
我修复了这个安装专用的react fa软件包的问题,但仍然不知道为什么上面的方法不起作用。但这可以工作:
docker exec /path/to/script.sh
答案 1 :(得分:0)
我怀疑您的ico
属性中的空格可能是问题。通常,这对州/道具不是问题。这可能归因于上下文。这可能会解决:
<i className={`fas ${theme.ico}`} />
仅使用更改ico
和fa-moon
的类替换上下文fa-sun
属性