useContext步骤
共3步:
1. 导入并调用createContext方法,得到Context对象,导出
import { createContext } from 'react'
export const Context = createContext()
2. 使用 Provider 组件包裹根组件,并通过 value 属性提供要共享的数据
return (
<Context.Provider value={ 这里放要传递的数据 }>
<根组件的内容/>
</Provider>
)
3. 在任意后代组件中,如果希望获取公共数据:
导入useContext;调用useContext(第一步中导出的context) 得到value的值
import React, { useContext } from 'react'
import { Context } from './index'
const 函数组件 = () => {
const 公共数据 = useContext(Context)
return ( 函数组件的内容 )
}
示例
index.js
// 1.导入createContext方法
import { useState, createContext } from 'react'
import reactDom from 'react-dom'
import Parent from './Parent'
// 2. 调用createContext方法,得到Context对象,导出
export const Context = createContext()
export default function App () {
const [color, setColor] = useState('red')
return (
// 3. 使用 **Provider** 组件**包裹根组件**,并通过 **value** 属性提供要共享的数据
<Context.Provider value={color}>
<div style={{ border: '1px solid #000' }}>
根组件color:{color}
<button onClick={() => { setColor('green') }}>点击更改颜色为green</button>
<Parent></Parent>
</div>
</Context.Provider>
)
}
reactDom.render(<App></App>, document.querySelector('#root'))
parent.js
import Son from './Son'
export default function Parent () {
return (
<div style={{ border: '1px solid #ccc', margin: 10 }}>
父组件
<Son></Son>
</div>
)
}
Son.js
// 4.导入useContext
import { useContext } from 'react'
// 5.调用useContext(第一步中导出的context)
import { Context } from './index'
export default function Son () {
// 6. 得到value的值
const color = useContext(Context)
console.log(color)
return (
<div style={{ border: '1px solid #ccc', margin: 10 }}>
子组件coler:{color}
</div>
)
}
点击按钮后
拓展-使用 ESLint 插件帮助检查 Hooks 的使用
使用 Hooks 的一些特性和要遵循的规则,那么应用到日常的开发中,就必须时刻注意不能写错。
包括这么三点:
-
在 useEffect 的回调函数中使用的变量,都必须在依赖项中声明;
-
Hooks 不能出现在条件语句或者循环中,也不能出现在 return 之后;
-
Hooks 只能在函数组件或者自定义 Hooks 中使用。
React 官方为我们提供了一个 ESLint 的插件,专门用来检查 Hooks 是否正确被使用,它就是 eslint-plugin-react-hooks 。通过这个插件,如果发现缺少依赖项定义这样违反规则的情况,就会报一个错误提示(类似于语法错误的提示),方便进行修改,从而避免 Hooks 的错误使用。
使用步骤
使用步骤
-
安装这个插件:
npm install eslint-plugin-react-hooks -D
-
修改:ESLint 配置文件。
加入两个规则:rules-of-hooks 和 exhaustive-deps。如下:
{
"plugins": [
// ...
"react-hooks"
],
"rules": {
// ...
// 检查 Hooks 的使用规则
"react-hooks/rules-of-hooks": "error",
// 检查依赖项的声明
"react-hooks/exhaustive-deps": "warn"
}
}