我使用钩子在LessonThemes组件,使用上下文,我尝试访问Test中的color
值组件,但我得到一个错误
对象不可迭代(不能读取属性Symbol (Symbol.iterator))
LessonThemes.jsx
import React, {useState, useEffect, createContext} from "react";
import ThemeContext from "./ThemeContext";
export const CounterContext = createContext();
export default function LessonThemes(props) {
const [color, setColor] = useState(localStorage.getItem("color"));
const [themes, setThemes] = useState([
{ name: "G", color: "green" },
{ name: "R", color: "red" },
{ name: "B", color: "blue" },
])
useEffect(() => {
localStorage.setItem("color", color);
})
const SideBarPageContent = (SideBarPageContentBackground) => {
localStorage.setItem('color', SideBarPageContentBackground);
setColor(SideBarPageContentBackground);
}
return (
<CounterContext.Provider value={[color, setColor]}>
{
themes.map((theme, index) => {
return (
<label key={index}>
<input
onChange={() => SideBarPageContent(theme.color)}
type="radio"
name="background"
/>{theme.name}</label>
);
})
}
</CounterContext.Provider>
);
}
Test.jsx
export default function Test(props) {
const [color] = useContext(LessonThemes);
return (
<div>
<div className="sidebar-brand-container">
<LessonThemes />
</div>
<div>
<span style={{ background: color }} href="#">Theme</span>
</div>
</div>
);
}
LessonThemes
是一个react组件,它为它的子组件提供上下文。CounterContext
是您需要在Test
中访问的上下文。
import { CounterContext } from '../path/to/CounterContext';
export default function Test(props) {
const [color] = useContext(CounterContext);
return (
<div>
<div className="sidebar-brand-container">
<LessonThemes />
</div>
<div>
<span style={{ background: color }} href="#">Theme</span>
</div>
</div>
);
}
你可能还应该定义一个初始上下文值,以防Test
没有被渲染成一个具有CounterContext
作为祖先的React DOMTree。
export const CounterContext = createContext([]);