您好,登錄后才能下訂單哦!
要使用React的Context API實現跨組件狀態共享,首先需要創建一個包含共享狀態的上下文對象。然后,將這個上下文對象提供給所有需要訪問共享狀態的組件。
以下是一個簡單的示例:
// SharedStateContext.js
import React, { createContext, useState } from 'react';
const SharedStateContext = createContext();
const SharedStateProvider = ({ children }) => {
const [sharedState, setSharedState] = useState('');
return (
<SharedStateContext.Provider value={{ sharedState, setSharedState }}>
{children}
</SharedStateContext.Provider>
);
};
export { SharedStateContext, SharedStateProvider };
// App.js
import React from 'react';
import { SharedStateProvider } from './SharedStateContext';
import ComponentA from './ComponentA';
import ComponentB from './ComponentB';
const App = () => {
return (
<SharedStateProvider>
<ComponentA />
<ComponentB />
</SharedStateProvider>
);
};
export default App;
// ComponentA.js
import React, { useContext } from 'react';
import { SharedStateContext } from './SharedStateContext';
const ComponentA = () => {
const { sharedState, setSharedState } = useContext(SharedStateContext);
return (
<div>
<h1>Component A</h1>
<p>Shared state: {sharedState}</p>
<button onClick={() => setSharedState('Hello from Component A')}>Update State</button>
</div>
);
};
export default ComponentA;
// ComponentB.js
import React, { useContext } from 'react';
import { SharedStateContext } from './SharedStateContext';
const ComponentB = () => {
const { sharedState, setSharedState } = useContext(SharedStateContext);
return (
<div>
<h1>Component B</h1>
<p>Shared state: {sharedState}</p>
<button onClick={() => setSharedState('Hello from Component B')}>Update State</button>
</div>
);
};
export default ComponentB;
通過以上步驟,就可以在ComponentA和ComponentB中共享狀態,并且在一個組件中更新狀態后,另一個組件也會同步更新。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。