1- Create a Context constant and export it
We will import this constant(const) in all functions which we will be using the context. I will name the file Context.js
//Context.js
import React from "react";
export const Context = React.createContext();
2- In App.js Import and provide the context to all Functional Components
//App.js
import React, { useState } from "react";
import { Context } from "./Context.js";
import ComponentA from "./ComponentA";
import ComponentB from "./ComponentB";
export default function App() {
const [context, setContext] = useState("default context value");
return (
<Context.Provider value={[context, setContext]}>
<ComponentA />
<ComponentB />
</Context.Provider>
);
}
To do that we do 3 things :)
a- Import the Context we created in 1st step
b- Create a state (via useState) which we will share between components.
c- Wrap components with Context.Provider and pass the state(context) and a function(setContext) to update the state which we created in step b.
3- Consume and set/change value of the context in child components.
//ComponentA.js
import React, { useContext } from "react";
import { Context } from "./Context";
export default function ComponentA() {
const [context, setContext] = useContext(Context);
return (
<div>
ComponentA:
<button onClick={() => setContext("New Value")}>
Change Context Value
</button>
</div>
);
}
//ComponentB.js
import React, { useContext } from "react";
import { Context } from "./Context";
export default function ComponentB() {
const [context, setContext] = useContext(Context);
return <div>ComponentB: {context}</div>;
}
To consume and change the value of context:
a- Import Context we created in step 1.
b- Import useContext from "react"
c- Consume value of context via useContext and use it like a state variable (see ComponentB)
d- Change the value via setContext function which we get from useContext (see ComponentA)
Full Code:
<iframe src="https://codesandbox.io/embed/v36ew" style="width:100%; height:calc(300px + 8vw); border:0; border-radius: 4px; overflow:hidden;" allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb" loading="lazy" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"> </iframe>

所有评论(0)