簡體   English   中英

如何正確更改 React 上下文值?

[英]How to properly change React context value?

假設我已聲明具有以下上下文:

const ColorContext = React.createContext(“”)

我正在嘗試創建一個簡單的 function ,它可以更改上下文的值,稍后可以在許多其他組件中用作全局變量 state 。 我已經實現的 function 但是沒有做任何改變上下文值的事情,這是我所做的,請隨時告訴我我在代碼中哪里出錯了:

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>
  );
}

代碼沙箱中的說明和代碼希望對您有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM