useContext可以用来实现组件间跨级通信(祖孙组件通信,不需要props一级一级向下传)
步骤:
①首先创建Context:const newContext=React.createContext(initValue)
②用<newContext.Provider><newContext.Provider/>包裹需要接收数据的组件
③获取数据:const data=useContext(newContext)
实例:
import React, { useState, useContext } from 'react';
// 1. 创建context
const themeContext = React.createContext('#000')
// 孙子组件
const Child = (props) => {
// 3. 使用useContext(themeContext)接收数据bgColor
const bgColor = useContext(themeContext)
const style = { backgroundColor: bgColor };
return (<div style={style}>Child
</div>)
}
// 中间组件
const Demo = () => {
return (
<div>
<Child />
</div>
)
}
// 最外层组件
export default function ContextDemo() {
const [bgColor, setBgColor] = useState('#000')
return (<div>
<button onClick={() => setBgColor('red')}>改变颜色</button>
{/* 2. 使用themeContext.Provider包裹需要数据的组件 */}
<themeContext.Provider value={bgColor}>
<Demo />
</themeContext.Provider>
</div>)
}