0

我收到此错误(其中包括):

Type 'Dispatch<SetStateAction<null>>' is not assignable to type '() => void'

我基本上有这个:

import React, {
  ReactElement,
  ReactNode,
  useEffect,
  useRef,
  useState,
  useContext,
} from 'react';

export const ScrollToContext = React.createContext({
  ref: React.createRef(),
  setScrollTo: () => {},
});

export function useScrollTo() {
  return useContext(ScrollToContext);
}

我希望上下文提供程序的值具有 2 个属性: aref和 a setScrollTo,它是一个 setState 函数。如何在 TypeScript 中输入这些内容?

如何正确初始化React.createContext,如何输入useScrollTo()返回值?

export function useScrollTo(): ??? {
  return useContext(ScrollToContext);
}
4

1 回答 1

1

您可以使用接口来指定上下文的类型。尝试这个:

interface IScrollToContext {
  ref: RefObject<undefined>;
  setScrollTo: Dispatch<SetStateAction<string>>; // I am assuming the state type is a string
}

// Now you can initialize it without errors
export const ScrollToContext = createContext<IScrollToContext>({
  ref: createRef(),
  setScrollTo: () => {},
});

您不需要指定useScrollTo函数挂钩的返回类型。Typescript 为您推断类型。但是,如果您想明确地这样做,请执行以下操作:

export function useScrollTo(): IScrollToContext  {
  return useContext(ScrollToContext);
}
于 2021-11-10T00:18:19.977 回答