reactjs - 无法在 typescript 中声明 React 上下文?

标签 reactjs typescript react-hooks react-context

我正在尝试在 typescript 中使用钩子(Hook)创建一个上下文,如下所示:

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?我收到一条错误消息

'Cannot find namespace 'SettingsStateContext'

我该如何解决这个问题?

最佳答案

我不确定你的第二次导出。这是我的使用方法:

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;
`

关于reactjs - 无法在 typescript 中声明 React 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59021426/

相关文章:

javascript - 为什么使用 Hooks 的 ReactJS 组件会根据开发者控制台是否打开而呈现一次或两次?

reactjs - 与之前使用自定义钩子(Hook)的渲染相比,渲染了更多的钩子(Hook)

reactjs - 为什么 webpack 在我的包中包含椭圆 bn.js 模块

javascript - 将函数作为两层深度的 props 传递

javascript - 在 Angular 服务中包含 Jquery

typescript - 在 mac 上构建后在 Electron 应用程序中找不到模块

javascript - ionic 混合移动应用程序获取设备位置

javascript - 导航离开后间隔未清除

reactjs - Material-table:如何为 EmptyDataSourceMessage 提供自定义样式

javascript - 构建高阶组件并将其应用于 redux connect