context 主要用于解决多层级嵌套传值问题,如果用props 层层传递,较为繁琐 下面举个小例子说明
import React from 'react'
import { useContext } from 'react'
type Props = {}
const themes = {
light: {
foreground: "#000000",
background: "#eeeeee"
},
dark: {
foreground: "#ffffff",
background: "#222222"
}
}
//生产者
const ThemeContext = React.createContext(themes);
// const context = (props: Props) => {
// return (
// <div>context</div>
// )
// }
// export default context
// 生产theme主题
export default () => {
return <ThemeContext.Provider value={themes.dark}>
<Toolbar/>
</ThemeContext.Provider>
}
const Toolbar = (params) => {
return <ThemeButton></ThemeButton>
}
const ThemeButton = (params) => {
// 消费,返回顶层组件传递的context值
const theme = useContext(ThemeContext);
console.log('theme', theme)
return <button style={{background:theme.background}}>helleo</button>
}