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

React TypeScript父子组件传函数出现类型不匹配(签名看似一致)

问题解决:React + TypeScript 组件传参报错及状态更新错误

核心问题分析

  1. UI组件props接收方式错误:React组件的参数是一个props对象,你直接把函数作为参数传入,TypeScript会识别为类型不匹配。
  2. 数组拷贝逻辑错误:{...items}会把数组转换成普通对象,无法调用push方法,导致状态更新失效。
  3. 缺少UI组件的props类型定义:没有明确声明UI组件接收的props结构,TypeScript无法完成类型校验。

修改后的代码

App.tsx

import { useState } from 'react';
import UI from './UI';
// 请确保Graph和NodeList组件已正确导入

// 重命名类型避免和React Props概念混淆
interface ItemType {
  name: string;
  dependencyList: string[];
}

function App() {
  const starter: ItemType[] = [];
  const [items, setItems] = useState<ItemType[]>(starter);

  const addItem = (name: string, dependencyList: string[]) => {
    // 用展开运算符正确拷贝数组
    const listsCopy = [...items];
    const newItem: ItemType = { name, dependencyList };
    listsCopy.push(newItem);
    setItems(listsCopy);
  };

  return (
    <div className="main">
      <div className="UI">
        <h1>Add/Edit Item</h1>
        <UI handleAddItem={addItem} />
      </div>
      <div className="Visual">
        <h1>Graph Visualization</h1>
        <Graph />
      </div>
      <div className="NodeList">
        <h1>Item List</h1>
        <NodeList />
      </div>
    </div>
  );
}

export default App;

UI.tsx

import "../styles/UI.css";

// 明确声明UI组件的props类型
interface UIProps {
  handleAddItem: (name: string, dependencyList: string[]) => void;
}

// 组件接收props对象并解构取出方法
function UI({ handleAddItem }: UIProps) {
  // 示例:后续可在此实现用户输入表单逻辑
  return (
    <>
      <form onSubmit={(e) => {
        e.preventDefault();
        // 模拟调用添加方法,实际可替换为真实输入值
        handleAddItem("测试项", ["依赖A", "依赖B"]);
      }}>
        <button type="submit">添加项目</button>
      </form>
    </>
  );
}

export default UI;

关键修改说明

  • UI组件传参规范:通过UIProps接口定义props结构,组件接收props对象并解构,符合React组件标准写法,TypeScript可正确校验传入的方法类型。
  • 数组拷贝修复:用[...items]创建数组浅拷贝,保证结果是数组类型,能正常调用push方法,同时避免直接修改原状态数组。
  • 类型命名优化:将原Props改名为ItemType,避免和React组件的props概念混淆,提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:55:22