Hooks全部入门
useState
useEffect
useContext
useRef
重要:自定义hooks
context可以看作是上下文
是什么:
- 创建一个上下文环境,在上下文环境中保持变量
怎么用:
2. 创建context -> createContext
3. 使用Provider圈定作用域
4. 在作用域内使用useContext来使用上下文
demo
import React, { createContext, useContext, useState } from 'react';
const C = createContext(null);
function useContextDemo() {
const [ n, setN ] = useState(0);
return (
<C.Provider value={{n, setN}}>
<div>
<Parent />
</div>
</C.Provider>
)
}
function Parent() {
const {n} = useContext(C);
return (
<div>
this is parent
<p>this is n in parent :{ n}</p>
<ChildA />
<ChildB />
</div>
)
}
function ChildA() {
const {n, setN} = useContext(C);
return (
<div>
this is child
<p>this is n in childA :{ n}</p>
<button onClick={() => { setN(n + 1) }}>+1</button>
</div>
)
}
function ChildB() {
const {n, setN} = useContext(C);
return (
<div>
this is child
<p>this is n in childB :{ n}</p>![在这里插入图片描述](https://img-blog.csdnimg.cn/2020042120203162.gif)
<button onClick={() => { setN(n + 1) }}>+1</button>
</div>
)
}
export default useContextDemo;
- 首先第三行使用createContext创建一个context并赋值给C
- 在最外层组件使用C.Provider包裹要使用的组件
- 在ChildA组件和ChildB组件分别引入context结构出来的n和setN
- 在Provider范围内的点击任意一个按钮都可以实现setN的效果,并且在任意位置使用n都可以获取到n