reactjs - 为什么 React Context 对对象和数组的行为不同?
问题描述
所以我正在尝试构建一个基本的主题转换器应用程序,但在中途我尝试放置对象值。
这是存储样式表的对象。
const Theme = {
light:{
textColor:"#000",
backgroundColor:"#fff"
},
dark:{
textColor:"#fff",
backgroundColor:"#000"
}}
导出默认主题;
案例 1:我尝试在上下文和状态中使用数组作为默认值
const themeContext = createContext(["light"]);
const theme = useContext(themeContext)[0];//theme is whatever is in context array
const currentTheme = Theme[theme]//current theme will be the value of themecontext in 0th position in array
const themeHook = useState("light"); //write theme in state, so when app starts it has a default theme at that time
案例 2:现在如果我尝试将默认值添加为对象,它不起作用:
const themeContext = createContext(Theme.dark);
const theme = useContext(themeContext);
const currentTheme = theme;
const themeState = useState(Theme.dark);
我用它来访问数据:
<h1
style={{
color:`${currentTheme.textColor}`,
backgroundColor:`${currentTheme.backgroundColor}`
}}
>
Hello Boiss
</h1>
谁能告诉我为什么?
解决方案
推荐阅读
- ios - Swift 从 ViewController 向 ViewController 发送数据
- selenium-webdriver - 如何解决“找不到日志类型'性能'”问题?
- php - 如何在return语句中编写循环?
- python - (Python) 在线程中关闭 pygame.display
- mysql - SQL查询查找在某些2日期增加值的所有产品
- php - 单个 PHP 文件,可以擦除包含子文件夹的文件夹内的所有内容以及文件本身
- python - 如何转换类型”
" 在 python 中听写 - javascript - 两个不同数组的 addEventListener - forEach -代码优化
- python - LightGBM - sklearnAPI 与训练和数据结构 API 以及 lgb.cv 与 gridsearchcv/randomisedsearchcv
- angular - 如何将 promise.all 转换为 observables