有时必须传递useState
钩子的setter函数。输入这个函数的正确方法是什么?
// some component with useState
const [infoText, setInfoText] = useState<string>("");
// same component calls a function in which the setter function is needed.
getInfoText(setInfoText);
// in the definition of that function (getInfoText) I now want to correctly type the setter function
export function getInfoText(setInfoText: ???) {
注:我知道有几个类似的问题。我想提供一个没有上下文的一般性问题,例如:这段代码的正确类型是什么?
React中的状态设置器类型为Dispatch<SetStateAction<TypeOfTheState>>
,其中Dispatch
、SetStateAction
可以从"react"
导入。例如:
import { Dispatch, SetStateAction, useState } from "react";
export default function Component() {
// The type of setInfoText is Dispatch<SetStateAction<string>>
const [infoText, setInfoText] = useState<string>("");
// We can give it as an argument to foo, as it's typed below
foo(setInfoText);
return <></>;
}
function foo(stateSetter: Dispatch<SetStateAction<string>>) {}