You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

传递setState函数作为props时指定类型仍触发类型错误

问题分析与解决方案

问题根源

你遇到的类型错误是因为setTags的类型(Dispatch<SetStateAction<string[]>>)和TagInput组件onChange props的类型((tags: string[]) => void)不兼容:

  • Dispatch<SetStateAction<string[]>>允许传入两种参数:直接的string[]值,或者返回string[]的回调函数
  • 但TagInput定义的onChange只接受string[]作为参数,更严格的类型要求导致赋值时触发报错
  • TagInput内部无报错是因为它仅以string[]为参数调用onChange,符合自身的类型定义

解决方案

有两种常见的修复方式:

方式1:修改TagInput的props类型,兼容Dispatch类型

直接把onChange的类型调整为React内置的Dispatch<SetStateAction<string[]>>,这样可以直接传递setTags:

// TagInput.tsx
import { Dispatch, SetStateAction } from 'react';

interface Props {
  tags: string[];
  onChange: Dispatch<SetStateAction<string[]>>;
}

const TagInput = ({ tags, onChange }: Props) => {
  // 组件逻辑不变
};

方式2:在父组件中包装函数适配类型

如果不想修改TagInput的类型,可以在传递onChange时用匿名函数包装setTags,把它适配为仅接受string[]的函数:

// App.tsx
<TagInput 
  tags={tags} 
  onChange={(newTags) => setTags(newTags)} 
/>

内容的提问来源于stack exchange,提问作者hse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:40:24