reactjs - 如何将 setter 钩子(Hook)传递给子组件并满足 TypeScript

标签 reactjs typescript react-hooks

我想将一个 setter 钩子(Hook)(setValuesList)从父级(App.tsx)传递给子组件(AddNumber.tsx)
我在父组件中定义了这样的钩子(Hook):

const [valuesList, setValuesList] = useState<number[]>([]);
我想像这样将钩子(Hook)传递给子组件:
<AddNumber valuesList={valuesList} setValuesList={setValuesList} />
但是我收到一个 typescript 错误:
(JSX attribute) AppProps.setValuesList: (num: number) => void
Type 'Dispatch<SetStateAction<number[]>>' is not assignable to type '(num: number) => void'.
  Types of parameters 'value' and 'num' are incompatible.
    Type 'number' is not assignable to type 'SetStateAction<number[]>'.ts(2322)
AddNumber.tsx(5, 3): The expected type comes from property 'setValuesList' which is declared here on type 'IntrinsicAttributes & AppProps'
在子组件中,我为这样的 Prop 定义了一个接口(interface):
interface AppProps {
  valuesList: number[];
  setValuesList: (num: number) => void;
}
有谁看到我在这里做错了什么?
我的存储库位于:https://github.com/acandael/number-list
谢谢你的帮助,
安东尼

最佳答案

这是 useState 的类型定义钩

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
因此,如果您传递类型 number[]调用 useState 时的状态值setter 函数的类型将是 React.Dispatch<SetStateAction<number[]>>
import { SetStateAction } from 'react';

// this interface will satisfy if you want to pass setValuesList directly
interface AppProps {
  valuesList: number[];
  setValuesList: React.Dispatch<SetStateAction<number[]>>;
 
  // setValuesList: (val: number[]) => void  will also satisfy, but it is
  // better to be explict and pass React.Dispatch<SetStateAction<number[]>>
}
如果您不想修改界面,您可以创建并传递另一个函数。
// you don't need to modify the interface if you take this approach -
// the interface already satisfies the type required in this case
const updateValue = (num: number) => {
 setValuesList(prev => prev.concat(num))
}

<AddNumber valuesList={valuesList} setValuesList={updateValue} />

关于reactjs - 如何将 setter 钩子(Hook)传递给子组件并满足 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62937947/

相关文章:

javascript - Javascript 中缺少模块,但 Typescript 中没有

reactjs - Flatlist scrollToIndex with Hooks useRef

typescript - 我想在从 index.ts 导入文件时在 eslint 中出错

javascript - 当它是 void 函数时,如何在 TypeScript 中输入异步函数

react-native - useRef 钩子(Hook)不适用于 lottie-react-native

firebase - 太多渲染 react 钩子(Hook)、useEffect、map

javascript - 类型错误 : Cannot read property 'calls' of undefined

reactjs - 获取状态并从中间件进行调度

reactjs - HTML Canvas,带有 React 钩子(Hook)和 Typescript

javascript - 即使事件已传递给调度程序,Reducer 仍显示未定义