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

React TypeScript:传递Children与Props时遇类型错误求解决

解决TypeScript类型错误:传递Props给Layout组件时提示属性不存在

问题根源

你的Layout.tsx组件参数写法错误——当前把children单独解构作为第一个参数,第二个参数的props并不是组件接收的外部props(React组件仅接收一个props对象作为参数,第二个参数是可选的上下文)。同时未给Layout定义正确的TypeScript类型,导致编译器无法识别你传入的isVisible和message属性。

修复步骤

1. 修正Layout组件的参数与类型定义

修改Layout.tsx,先明确组件接收的props类型,再从同一个props对象中解构所有需要的属性:

import React from "react";
import Alert from "../global/Alert";

// 定义Layout接收的Props类型
type LayoutProps = {
  children: React.ReactNode;
  isVisible: boolean;
  message: {
    title: string;
  };
};

export default function Layout({ children, isVisible, message }: LayoutProps) {
  // ... 你的原有逻辑代码

  return (
    <main className={styles.main}>
      {/* 直接使用解构后的属性传递给Alert */}
      <Alert isVisible={isVisible} message={message} />
      
      {/* ... 页面其他元素 */}

      <section className={styles.content} style={{ transform: `translateY(${(isOpenNav === "false") ? "0vh" : "-45vh"})` }} onClick={() => setIsOpenNav("false")}>
        {children}
      </section>

      {/* ... 页面其他元素 */}
    </main>
  );
}

2. (可选)优化Alert组件的类型定义

将Alert的props: any替换为明确的类型,提升代码类型安全性:

import styles from "./styles/Alert.module.scss";

// 定义Alert接收的Props类型
type AlertProps = {
  isVisible: boolean;
  message: {
    title: string;
  };
};

export default function Alert({ isVisible, message }: AlertProps) {
  return (
    <main className={styles.main} style={{ display: isVisible ? "flex" : "none" }}>
      {message.title}
    </main>
  );
}

3. ShopItem组件无需修改

你的ShopItem.tsx中传递isVisible和message的写法是正确的,修复Layout的类型后,TypeScript错误会自动消失。

修复逻辑说明

  • React组件仅接收一个props对象作为参数,所有外部传入的属性都包含在这个对象中,之前的({ children }, props: any)写法完全错误。
  • 明确的TypeScript类型定义能让编译器正确校验传入的属性,避免类型不匹配的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:15:17