【发布时间】:2019-07-18 01:46:06
【问题描述】:
如果我有Comp1.js
const Comp1 = () => {
const globalTheme = new createContext()
return (
<globalTheme.Provider globalStyle={anyVar}>
<Layout>
<AnotherComponent />
</Layout>
</globalTheme.Provider>
)
}
然后在layout.js
const globalStyle = useContext(globalTheme)
console.log(globalStyle)
我收到globalTheme is not defined,我应该再次创建上下文吗?
const globalTheme = new createContext()
const globalStyle = useContext(globalTheme)
console.log(globalStyle)
然后我得到undefined for globalStyle
我错过了什么?
编辑:基于 cmets,我使用第三个文件并导入上下文以访问它 -> theme-context.js
import { createContext } from 'react'
export const themes = {
light: {
foreground: '#000000',
background: '#eeeeee',
},
dark: {
foreground: '#ffffff',
background: '#222222',
},
}
export const ThemeContext = createContext(
themes.dark // default value
)
然后我在另一个文件 blog-template.js 中提供这个上下文
import { ThemeContext } from '../context/theme-context'
import Layout from '../components/layout'
const Blog = () => {
let globalStyle = 'just any value'
return (
<ThemeContext.Provider globalStyle={globalStyle}>
<Layout />
</ThemeContext.Provider>
)}
然后在layout.js
import React, { useContext} from 'react'
import { ThemeContext } from '../context/theme-context'
const Layout = () => {
const globalStyle = useContext(ThemeContext)
console.log(globalStyle)
}
但是globalStyle 是未定义的,这是为什么呢?
编辑:错误是没有提供价值作为道具
-<ThemeContext.Provider globalStyle={globalStyle}>
+-<ThemeContext.Provider value={globalStyle}>
【问题讨论】:
标签: reactjs react-hooks react-context