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

如何创建包含必填无默认、可选带默认值的React TypeScript组件

解决方案

你遇到的TS报错和代码问题核心有两点:

  1. 原代码在defaultProps中为必填项children设置了默认值,且单独书写的children属于未定义变量,本身就是语法错误
  2. 实际运行的代码没有给组件参数显式绑定你定义的LazyLoadCompProps类型,导致TS无法识别children的类型,抛出隐式any的错误
修改实现(满足children必填无默认值的要求)

直接修改代码如下:

import React from "react";
import { Suspense } from "react";
import Loading from "../Loading/Loading";

interface LazyLoadCompProps {
  children: React.ReactNode;
  height?: string;
  width?: string;
}

// defaultProps仅存放可选参数的默认值,必填的children不加入
const defaultProps: Partial<LazyLoadCompProps> = {
  height: "300px",
  width: "300px"
}

// 给props显式绑定类型
const LazyLoad = (props: LazyLoadCompProps) => {
  const {children, height, width} = props;

  return (
    <Suspense fallback={<Loading height={height} width={width} />}>
      {children}
    </Suspense>
  );
};

LazyLoad.defaultProps = defaultProps;

export default LazyLoad;
效果说明
  • children被标记为必填项,调用LazyLoad组件时不传children会直接触发TS类型报错
  • height和width保持可选,不传时默认使用300px的配置
  • 原有TS7031报错完全消除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:54:09