我收到此錯誤(其中包括):
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);
}
uj5u.com熱心網友回復:
您可以使用介面來指定背景關系的型別。嘗試這個:
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函式鉤子的回傳型別。打字稿為您推斷型別。但是,如果您想明確地這樣做,請執行以下操作:
export function useScrollTo(): IScrollToContext {
return useContext(ScrollToContext);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/354896.html
