图标类名不会在状态更改时更新
Posted
技术标签:
【中文标题】图标类名不会在状态更改时更新【英文标题】:Icon className doesn't update on state change 【发布时间】:2020-06-17 12:48:35 【问题描述】:我正在尝试最简单的主题切换以响应上下文,并且似乎无法在上下文更改时重新渲染图标。其他一切都很好:颜色,背景图像......它根据初始状态呈现任何一个图标,但切换主题时图标不会更新。
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
【问题讨论】:
【参考方案1】:我修复了这个安装专用的 react fa 包,仍然不知道为什么上面不起作用。这虽然有效:
import FontAwesomeIcon from "@fortawesome/react-fontawesome"
import faMoon from "@fortawesome/free-solid-svg-icons"
import faSun from "@fortawesome/free-solid-svg-icons"
//.....
return (
<li
style= background: theme.bgPrimary, color: theme.text
onClick=toggleTheme
>
isDarkMode ? (
<FontAwesomeIcon icon=faSun />
) : (
<FontAwesomeIcon icon=faMoon />
)
</li>
【讨论】:
【参考方案2】:我怀疑您的 ico
属性中的空格可能是问题所在。通常这不是状态/道具的问题。上下文可能要为此负责。这可能会解决它:
<i className=`fas $theme.ico` />
将您的上下文 ico
属性替换为仅更改 fa-moon
和 fa-sun
的类
【讨论】:
以上是关于图标类名不会在状态更改时更新的主要内容,如果未能解决你的问题,请参考以下文章