如何创建包含必填无默认、可选带默认值的React TypeScript组件
解决方案
你遇到的TS报错和代码问题核心有两点:
- 原代码在
defaultProps中为必填项children设置了默认值,且单独书写的children属于未定义变量,本身就是语法错误 - 实际运行的代码没有给组件参数显式绑定你定义的
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
相关产品推荐
相关产品推荐

