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

React 18.2.0中如何设置类组件默认props?

React 18.2.0 类组件设置默认Props的正确方式

类组件的默认Props写法

先明确:函数组件的defaultProps确实被弃用了,但类组件的static defaultProps在React 18.2.0里完全没问题,官方依然支持,没有被弃用。

两种常用写法:

  • 类内部静态属性定义:
class MyClassComponent extends React.Component {
  // 直接在类里定义静态defaultProps
  static defaultProps = {
    title: '默认标题',
    count: 0
  };

  render() {
    return (
      <div>
        <h1>{this.props.title}</h1>
        <p>计数:{this.props.count}</p>
      </div>
    );
  }
}
  • 类外部挂载:
class MyClassComponent extends React.Component {
  render() {
    return (
      <div>
        <h1>{this.props.title}</h1>
        <p>计数:{this.props.count}</p>
      </div>
    );
  }
}

// 在类外面给组件挂载defaultProps
MyClassComponent.defaultProps = {
  title: '默认标题',
  count: 0
};

这两种写法都能在React 18.2.0中正常生效,官方文档也仍保留了相关说明,放心用就行。

关于Prop-types的误区

你说的“已弃用”是误解:Prop-types并没有被弃用,只是React把它从核心库拆分到了单独的prop-types npm包中,现在依然是无TypeScript项目里做props类型检查的常用工具,稳定性和兼容性都没问题。

如果觉得它不合适,想追求更严谨的类型检查,直接用TypeScript就行,示例如下:

import React from 'react';

// 用TypeScript接口定义props类型
interface MyComponentProps {
  title?: string;
  count?: number;
}

class MyClassComponent extends React.Component<MyComponentProps> {
  static defaultProps: Partial<MyComponentProps> = {
    title: '默认标题',
    count: 0
  };

  render() {
    return (
      <div>
        <h1>{this.props.title}</h1>
        <p>计数:{this.props.count}</p>
      </div>
    );
  }
}

TypeScript的静态类型检查比Prop-types更严格,适合追求代码健壮性的项目。

新手小提示

React这些年确实更新不少,但类组件的核心API(包括defaultProps)一直保持兼容,不用过度焦虑版本变化。先把基础用法吃透,再逐步尝试新特性(比如函数组件+Hook)就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:40:41