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

React TypeScript中forwardRef结合defaultProps报错问题求助

函数组件结合forwardRef使用defaultProps的问题及TypeScript与prop-types的关系

一、forwardRef结合defaultProps报错的解决方法

问题根源

你代码里存在两个关键问题:

  1. 将prop-types错误挂载到了组件的prototype属性上(正确应该是propTypes);
  2. 默认props挂在了原始的ComponentA函数上,但最终导出的是forwardRef包装后的新组件,原始组件的defaultProps不会被继承,导致默认值不生效。

修正后的代码

import React, { forwardRef } from "react"
import PropTypes from 'prop-types';

type Props = {
    children: JSX.Element | JSX.Element[],
    text: string,
    text1?: string,
} 

// 组件接收ref参数
const ComponentA = (props: Props, ref: React.Ref<HTMLAllCollection>) => {
    return <div ref={ref}>Hey
        {props.children}
        {props.text}
        {props.text1}
    </div>
}

// 正确挂载prop-types到propTypes属性
ComponentA.propTypes = {
    children: PropTypes.oneOfType([
        PropTypes.element,
        PropTypes.arrayOf(PropTypes.element)
    ]).isRequired,
    text: PropTypes.string.isRequired,
    text1: PropTypes.string
}

// 用变量接收forwardRef返回的组件,再挂载defaultProps
const ForwardedComponent = forwardRef<HTMLAllCollection, Props>(ComponentA)

ForwardedComponent.defaultProps = {
    text: 'done'
} as Partial<Props>

export default ForwardedComponent

关键说明

  • forwardRef会返回一个全新的组件实例,必须将defaultProps直接挂载到这个返回的组件上,才能让默认值生效;
  • 修正了prop-types的挂载属性:是ComponentA.propTypes而非ComponentA.prototype,后者是JS类的原型属性,和prop-types无关。

二、TypeScript环境下是否需要prop-types?

  • TypeScript提供编译时类型检查,在开发阶段就能拦截props类型不匹配、必填项缺失等问题,覆盖了prop-types大部分核心场景;
  • prop-types是运行时校验工具,仅在以下场景建议保留:
    • 你的组件需要提供给非TypeScript项目使用;
    • 存在编译时无法覆盖的动态props场景(比如后端返回数据直接作为props传入),需要运行时兜底校验。

如果项目完全基于TypeScript开发,且组件仅在内部TS环境中使用,完全可以移除prop-types,依赖TS的编译时检查即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:40:34