用打字稿反应上下文

时间:2020-08-31 13:05:28

标签: reactjs typescript react-context

我想在我的React Typescript项目中使用一个上下文,我该怎么做?

我有以下代码: App.js

import {Context} from 'context'

const App = () => {
  const [value, setValue] = useState("");
  return (
    <Router>
       <Context.Provider value={{value, setValue}}>
       ... some routes
       </Context.Provider>
    </Router>
  )
}

然后在我的context.js文件中:

import {createContext} from 'react';

type ValueContextType = {
  value: string;
  setValue: (value: string) => void;
}

export const ValueContext = createContext<ValueContextType | undefined>(undefined);

我想用它在另一个文件中设置状态。假设users.js

import {ValueContext} from 'context'

const Users () => {
  const {value, setValue} = useContext(ValueContext);
}

现在,值和setValue都具有相同的错误消息的问题:

属性'setValue'在类型'ValueContextType |中不存在未定义”

我该如何进行这项工作?

1 个答案:

答案 0 :(得分:0)

我找到了可行的解决方案:

App.js

import {Context} from 'context'

const App = () => {
  type ValueContextType = {
  value: string;
  setValue: (value: string) => void;
  }
  const [value, setValue] = useState<ValueContextType | any>("");
  return (
    <Router>
       <Context.Provider value={{value, setValue}}>
       ... some routes
       </Context.Provider>
    </Router>
  )
}

然后在我的context.js文件中:

import {createContext} from 'react';

type ValueContextType = {
  value: string;
  setValue: (value: string) => void;
}

export const ValueContext = createContext<ValueContextType | any>("");

users.js

import {ValueContext} from 'context'

const Users () => {
  const {value, setValue} = useContext(ValueContext);
}

我不知道这是不是“ hacky”,但它可以工作。