简体   繁体   English

如何在 typescript 中使用“useContext”?

[英]How to use "useContext" in typescript?

I am trying to make a dark/light theme system in my project, but I am having some problems with the code.我正在尝试在我的项目中创建一个深色/浅色主题系统,但我遇到了一些代码问题。

This line of code works fine in javascript:这行代码在 javascript 中运行良好:

const [darktheme, setDarkTheme] = useContext(ThemeContext);

But when I write it into typescript, I get 6 errors.但是当我将它写入 typescript 时,我得到 6 个错误。

I know that some of these variables need to have their type declared, but I only know the type of the darkTheme variable, which is a boolean.我知道其中一些变量需要声明其类型,但我只知道darkTheme 变量的类型,即boolean。

After I declare the types, 2 errors go away, but there is still 4 errors在我声明类型后,有 2 个错误 go 消失了,但仍然有 4 个错误

const [darktheme: boolean, setDarkTheme: any] = useContext(ThemeContext);

I used any after dark theme, which is not good practice but I didn't know the type我使用了任何 after dark 主题,这不是一个好习惯,但我不知道类型

Now I just get these errors:现在我得到这些错误: 在此处输入图像描述

在此处输入图像描述

I think that the main problem with my project is that I am trying to integrate javascript with typescript.我认为我的项目的主要问题是我正在尝试将 javascript 与 typescript 集成。 I don't know if that is normal or not, but I am doing it because some components are much easier to write with typescript, and some more basic components are better written in javascript.我不知道这是否正常,但我这样做是因为有些组件用 typescript 更容易编写,而一些更基本的组件最好用 javascript 编写。

Here is part of my app.js:这是我的 app.js 的一部分:

// Context

export const ThemeContext = React.createContext();

function App() {
  const [darkTheme, setDarkTheme] = useState(false);

  return (
    <ThemeContext.Provider value={[darkTheme, setDarkTheme]}>

,and when I use the function in this component, it works just fine: ,当我在这个组件中使用 function 时,它工作得很好:

import React, { useContext } from 'react';
import { ThemeContext } from '../App';

import Button from 'react-bootstrap/Button';

export default function DarkThemeTest() {
    const [darktheme, setDarkTheme] = useContext(ThemeContext);

    return (
        <Button onClick={() => {
            setDarkTheme(!darktheme);
        }}>
            Theme: {darktheme && "Dark" || "Light"}
        </Button>
    )
}

First, define a type for your context value首先,为您的上下文值定义一个类型

import { createContext, Dispatch, SetStateAction } from "react";

interface ThemeContextType {
  darkTheme: boolean;

  // this is the type for state setters
  setDarkTheme: Dispatch<SetStateAction<boolean>>; 
}

Then, create your context with this type and initialise it with a default value.然后,使用此类型创建您的上下文并使用默认值对其进行初始化。 This might seem unnecessary but it will avoid checking for null or undefined context later on这似乎没有必要,但可以避免稍后检查nullundefined的上下文

export const ThemeContext = createContext<ThemeContextType>({
  darkTheme: false,
  setDarkTheme: () => {}, // no-op default setter
});

Once you have created your state value and setter, set them into the context provider value创建 state 值和设置器后,将它们设置为上下文提供程序值

<ThemeContext.Provider value={{ darkTheme, setDarkTheme }}>

Now you can destructure the context value easily via useContext with full type support现在您可以通过具有完整类型支持的useContext轻松解构上下文值

const { darkTheme, setDarkTheme } = useContext(ThemeContext);

You could continue to use your array format though I wouldn't recommend it.尽管我不推荐它,但您可以继续使用您的数组格式。

type ThemeContextType = [boolean, Dispatch<SetStateAction<boolean>>];

export const ThemeContext = createContext<ThemeContextType>([false, () => {}]);

and

<ThemeContext.Provider value={[darkTheme, setDarkTheme]}>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM