[英]Using the context API in React
I'm starting to work with the context api in React, and I decided to make a simple theme context.我开始在 React 中使用上下文 api,我决定制作一个简单的主题上下文。 For now, if I go to my React DevTools and change the boolean isLightTheme to false, it works, but when i try to attach this functionality to a button, i keep getting errors.
现在,如果我将 go 更改为我的 React DevTools 并将 boolean isLightTheme 更改为 false,它可以工作,但是当我尝试将此功能附加到按钮时,我不断收到错误消息。 Can saomeone help me with that?
saomeone 可以帮我吗?
theme context主题语境
import React, { useState, createContext } from 'react'
export const ThemeContext = createContext()
export const ThemeContextProvider = ({ children }) => {
const [state, setState] = useState({
isLightTheme: true,
light: { syntax: '#555', ui: '#ddd', bg: '#eee' },
dark: { syntax: '#ddd', ui: '#333', bg: '#555' }
})
const toggleTheme = () => {
setState({ isLightTheme: !state.isLightTheme})
}
return (
<ThemeContext.Provider value={{...state, toggleTheme}}>
{children}
</ThemeContext.Provider>
)
}
import React, { useContext } from 'react'
import { ThemeContext } from '../context/ThemeContext'
export const ThemeToggler = () => {
const themeContext = useContext(ThemeContext)
const { toggleTheme } = themeContext
return (
<button onClick={toggleTheme}>Change Theme</button>
)
}
The useState
hooks API doesn't update a selective piece of state like setState
does. useState
挂钩 API 不会像setState
那样更新 state 的选择性片段。 It'll override the entire state.它将覆盖整个 state。 Here when you toggle the theme, the new state is only
{ isLightTheme: .state.isLightTheme}
with no light and dark keys.在这里切换主题时,新的 state 只有
{ isLightTheme: .state.isLightTheme}
没有明暗键。 You just need to handle this by only updating that piece of state.您只需要更新 state 即可处理此问题。 This should work:
这应该有效:
import React, { useState, createContext } from 'react'
export const ThemeContext = createContext()
export const ThemeContextProvider = ({ children }) => {
const [state, setState] = useState({
isLightTheme: true,
light: { syntax: '#555', ui: '#ddd', bg: '#eee' },
dark: { syntax: '#ddd', ui: '#333', bg: '#555' }
})
const toggleTheme = () => {
//preserve the remaining state also
setState({...state,isLightTheme: !state.isLightTheme})
}
return (
<ThemeContext.Provider value={{...state, toggleTheme}}>
{children}
</ThemeContext.Provider>
)
}
Hope this helps !希望这可以帮助 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.