// 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>
</>
)
}
这篇博客介绍了如何在React应用中使用Context API来实现状态管理。通过创建和导出Context,使用Provider组件包裹状态数据,并在子组件中利用useContext Hook获取和使用这些数据,实现了组件间的值传递,简化了深层组件间的状态传递。

807

被折叠的 条评论
为什么被折叠?



