(農場標題+1)
在用 React 的時候常會遇到一個 value 要往下往下往下往下傳給子元件用,當然可以一直 props 下去,但專案發散後會很難找到原始的 value 在哪,於是出現了整合的 hooks — useContext。
簡單寫一個絕對看得懂的 demo,create-react-app 創專案後
src 資料夾 只留檔案 index.js / hooks.js / context.js / App.js / Note.js
- index.js 不用改
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';ReactDOM.render(
<>
<App />
</>,
document.getElementById('root')
);
2. hooks.js 假設要傳來傳去的value在這抓( data 從 API 也可以擺在這)
import { useState } from "react";const useValue = () => {
const [value, setValue] = useState(1);
return {
value,
setValue,
};
};export { useValue };
3. context.js 重點:放一個空的 createContext({})
import { createContext } from "react";const AppContext = createContext({});export { AppContext};
4. App.js 重點:
- 在最外層用 AppContext.Provider 包起來
- 屬性 value 裡面就是所有要傳來傳去的東西{{ ooxx }}
import React from "react";
import { useValue } from "./hooks";
import { AppContext } from "./context";
import Note from "./Note";function App() {
const { value, setValue } = useValue();return (
<AppContext.Provider value={{ value }}>
<Note />
<button onClick={() => setValue(value + 1)}>add</button>
</AppContext.Provider>
);
}export default App;
5. Note.js 重點:
- 在元件中 import ‘AppContext’ from ‘./context’
- const {“value”} = useContext(AppContext)
import React, { useContext } from "react";
import { AppContext } from "./context";function Note() {
const { value } = useContext(AppContext);return (
<ul>
<li>hello world</li>
<li>{value}</li>
</ul>
);
}export default Note;
更簡短版本 demo
import React, { useState, useEffect, createContext, useContext } from 'react'
import './App.css'const StoreContext = createContext({})const StoreProvider = (props) => {
const [event, setEvent] = useState({})
useEffect(() => {
setEvent({ text: 'Hello!', name: 'molly' })
}, [])
return (
<StoreContext.Provider value={{ event }}>
{props.children}
</StoreContext.Provider>
)
}const TestComp = () => {
const storedEvents = useContext(StoreContext)
console.log(storedEvents)
return (
<div>
<p>{storedEvents.event.text}</p>
<p>{storedEvents.event.name}</p>
</div>
)
}function App() {
return (
<StoreProvider>
<TestComp />
</StoreProvider>
)
}export default App