如何正确地改变React上下文值?



假设我已经声明了以下上下文:

const ColorContext = React.createContext(“”)

我正在尝试创建一个简单的函数,可以改变上下文的值,以后可以在许多其他组件中作为全局状态变量使用。但是,我实现的函数没有做任何事情来改变上下文值,这是我所做的,随时让我知道我在代码中出错的地方:

function GlobalContext(){
const {color, setColor} = useContext(ColorContext);
const toGreen = () => {
setColor(‘green’);
};
return(
<>
<ColorContext.Provider value={{color, setColor}}>
<button onClick={toGreen}> Change Color </button>
<ColorContext.Provider/>
</>
)
}

你做错了。useContext用于树中低于上下文提供者的组件。在渲染Context.Provider的组件中,您需要这样做:

const [color, setColor] = useState();

所以整个东西看起来像这样:

const ColorContext = React.createContext();
const MyColorContextProvider = ({children}) => {
const [color, setColor] = useState(); 
const toGreen = () => setColor('green');
return (
<ColorContext.Provider value={{color,setColor}}>
{children}
<button onClick={toGreen}>Change to Green</button>
</ColorContext.Provider>
);
}

然后:

const MyChildComponent = () => {
const {color} = useContext(ColorContext);
return <>The color in context is {color}</>
}

你的应用程序可以是:

const App = () => {
return (
<MyColorContextProvider>
<MyChildComponent/>
</MyColorContextProvider>
);
}

Stackblitz: https://stackblitz.com/edit/react-gym2ku?file=src%2FColorContextProvider.js

  1. toGreen()作为参数传递给ColorContext
  2. 任何嵌套组件都可以使用toGreen()来改变颜色
// Created a New Context for global use
const ColorContext = createContext();
export default function GlobalContext() {
// I set the value of color to red using array destructuring
const [color, setColor] = useState('Red');
const toGreen = () => {
// I set the color to green when this function is called
setColor('Green');
}
return (
<div>
{/* I pass the both the color and the toGreen function as args, now they can be accessed by all nested components */}
<ColorContext.Provider value= {{color, toGreen}}>
<h1>Current Color is : {color}</h1>
<NestedComponent />
</ColorContext.Provider>
</div>
);
}
// I created a nested component
function NestedComponent() {
// useContext lets us access the values passed to ColorContext
const colorProvider = useContext(ColorContext);
return (
// When button is Clicked the toGreen function passed down is triggered
<button onClick={colorProvider.toGreen}>Change Color from {colorProvider.color} to Green</button>
);
}

代码沙盒中的解释和代码希望能有所帮助😄

最新更新