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

React-Ionic组件传递Props时触发TypeScript类型错误,求解决方案

我来帮你搞定这个TypeScript报错问题~

问题原因

这个报错的核心是:你的StoreView组件没有声明它能接收data这个自定义Props,TypeScript默认只允许组件接收内置的IntrinsicAttributes(比如key、ref这类原生属性),所以它不认你传的data。另外你传递的是状态更新函数setStoreData,命名成data有点语义模糊,建议改成更清晰的名字。

解决方案

1. 给StoreView定义Props类型

先导入必要的类型,然后声明组件能接收的Props接口,明确属性的类型:

import React, { useEffect, useState, Dispatch, SetStateAction } from 'react';
// 保留你的其他导入

// 定义组件接收的Props类型
// 如果知道res.store_id的具体类型(比如单个number/string),把any[]换成对应类型会更严谨
interface StoreViewProps {
  setStoreData: Dispatch<SetStateAction<any[]>>;
}

// 给组件指定Props类型
const StoreView: React.FC<StoreViewProps> = (props) => {
  // 可以解构出需要的属性,方便使用
  const { setStoreData } = props;

  return (
    <IonContent>
      {/* 现在你可以在这里使用setStoreData了 */}
    </IonContent>
  );
}

export default StoreView;

2. 调整Login组件的Props传递

把Props的名字改成更语义化的setStoreData(和函数名对应),避免混淆:

// Login组件其他代码不变
return (
  <IonPage>
    <IonContent>
      {/* 保留你的登录表单代码 */}
    </IonContent>
    <StoreView 
      setStoreData={setStoreData}
    />
  </IonPage>
);

额外优化建议

如果res.store_id不是数组类型(比如是单个数字/字符串),建议调整useState的初始值和类型,让代码更严谨:

// 在Login组件里修改状态声明
const [storeData, setStoreData] = useState<number | null>(null);

// 对应的StoreViewProps也要同步修改
interface StoreViewProps {
  setStoreData: Dispatch<SetStateAction<number | null>>;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:27:47