// 1.导入createContext 默认方法
// 2.使用内置createContext导出数据
// 3.使用Provider方法包裹数据
// 4.在需要接收的组件中导入createContext导出数据
// 5.在需要接收的组件中导入内置方法useContext
// 6.声明此方法const value = useContext(Context)
// 7.最后使用里面的属性和方法
祖父
import React, { useState, createContext } from 'react'
import Pands from './Pands'
// 使用内置createContext导出数据
export const Context = createContext()
export default function App () {
const [a, b] = useState(8)
const handleClick = () => {
b((a) => a + 1)
}
return (
<Context.Provider
value={{
a,
handleClick
}}
>
<div>
App
<hr />
<Pands></Pands>
</div>
</Context.Provider>
)
}
父.一层或者多层传值.都可以.
import React from 'react'
import Chidren from './Chidren'
export default function Pands () {
return (
<div>
Pands
<hr />
<Chidren></Chidren>
</div>
)
}
子
import React, { useContext } from 'react'
import { Context } from './App'
// 内置useContext接收数据
export default function Children () {
const value = useContext(Context)
return (
<>
Chidren
<h3>{value.a}</h3>
<button onClick={value.handleClick}>按钮</button>
</>
)
}