我正在尝试在打字稿中使用 react 中的钩子创建一个上下文,如下所示:
interface SettingsStateContextProps {
sort: string;
type: string;
price: string;
option_full: boolean;
option_rated: boolean;
option_free: boolean;
}
export const SettingsStateContext = React.createContext<
Partial<SettingsStateContextProps>
>({});
export const SettingsStoreProvider:any = ({ reducer, initialState, children }):any => (
<SettingsStateContext.Provider // ERROR HERE
value={useReducer(reducer, initialState)}
children={children}
/>
);
但出于某种原因,我不知道为什么我不能声明 SettingsStateContext.Provider?我收到一条错误消息
'找不到命名空间'设置状态上下文'
我该如何解决这个问题?
我不确定您的第二次导出。我如何使用它:
1( 导出上下文以在任何地方使用
import React, { useEffect } from 'react'
import { ThemeProvider } from 'styled-components'
// this is needed so that components using theme will see it's type
declare module 'styled-components' {
interface DefaultTheme extends Theme {}
}
interface Theme {
color: string
}
const defaultTheme = { color: 'red' }
export const ThemeContext = React.createContext<Partial<Theme>>({})
export const ThemeContextProvider = props => {
const [theme, setTheme] = useState<Theme>(defaultTheme)
return (
<ThemeContext.Provider value={{ theme }}>
{props.children}
</ThemeContext.Provider>
)
}
2(将组件包装到您想要获得主题访问权限的位置(我在应用程序的顶层使用了一次(:
import React from 'react'
import { ThemeContextProvider, Input } from '@frontend'
export const App = () => {
return (
<ThemeContextProvider>
<Input />
</ThemeContextProvider>
)
}
在组件中使用它(共享组件的示例(:
import styled from 'styled-components'
import React, { forwardRef } from 'react'
type MyProps = {
err?: boolean
}
export const Input = forwardRef<HTMLInputElement, MyProps>(({ err, ...rest }, ref) => {
return <StyledInput {...rest} ref={ref} />
})
const StyledInput = styled.input<MyProps>`
box-shadow: inset 0 0 0 1px ${({ err, theme }) => (err ? theme.badColor : theme.primaryColor)};
border-radius: 5px;
`
我看到这里你没有在React.createContent
后放任何方括号,你应该这样写React.createContext()
,
export const SettingsStateContext = React.createContext();
把你的逻辑放在括号里,我应该工作!
你可以在这里学习以了解更多信息!
谢谢!