useReact的应用场景:在组件间共享状态
假设现在有两个组件,想要共享状态,可以使用
React.createContext
创建一个context对象,为了方便在所有的组件中共享状态,我将创建context的文件抽离为 creatContext.js
#creatContext.js
import { createContext } from 'react'
const FatherContext = createContext()
export default FatherContext;
组件1:
# Child1
import React, { useContext } from 'react'
import FatherContext from '../context/creatContext'
export default function Child1() {
const { username } = useContext(FatherContext)
return (
<>
<h1>child1的username============={username}</h1>
</>
)
}
组件2:
#Child2
import React, { useContext } from 'react'
import FatherContext from '../context/creatContext'
export default function Child2() {
const { username } = useContext(FatherContext)
return (
<>
<h1>Child2的username============={username}</h1>
</>
)
}
父组件:
# FatherCom
import React from 'react'
import Child1 from './child1'
import Child2 from './child2'
// context对象
import FatherContext from '../context/creatContext'
export default function FatherCom() {
return (
<div>
我是父组件
<FatherContext.Provider value={{ username: '小明小红' }}>
<div>
<Child1></Child1>
<Child2></Child2>
</div>
</FatherContext.Provider>
</div>
)
}
运行结果
文件结构: