Hooks-useContext

useContetn接收一个 context 对象(React.createContext 的返回值),并返回该 context 的当前值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { createContext, useState, useMemo, useContext } from 'react';

const GlobalContext = createContext();

const App = () => {
const [a, updateA] = useState('');
const [b] = useState('');

const contextValue = useMemo(() => ({ a, b }), [a, b]);

return (
<GlobalContext.Provider value={contextValue}>
<ConsumeA />
<ConsumeB />
<input value={a} onChange={(e) => updateA(e.target.value)} />
</GlobalContext.Provider>
);
};

function ConsumeA() {
const { a } = useContext(GlobalContext);

return a;
}

function ConsumeB() {
const { b } = useContext(GlobalContext);

console.log('render b with: ', b);

return b;
}

export default App;

参考:
https://zhuanlan.zhihu.com/p/346616580
https://zh-hans.reactjs.org/docs/hooks-reference.html#usecontext
https://github.com/facebook/react/issues/15156

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×