祖父
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>
</>
)
}