FumadocsZDecode
React

Props 默认值处理

在 React 中,当父组件不传递某个 prop 时,该 prop 的值默认为 undefined。设置默认值可以让组件更灵活,避免需要每次都显式传递相同的值。React 提供了三种方式来处理 props 的默认值。


一、getDefaultProps(ES5,已过时)

getDefaultProps 是 React 在 ES5 中使用 React.createClass 时的设置默认值方法。现在基本已被废弃,但在维护旧项目时可能会遇到。

const Button = React.createClass({
  getDefaultProps() {
    return {
      text: 'Click me',
      type: 'primary',
    }
  },
  render() {
    return <button className={this.props.type}>{this.props.text}</button>
  },
})

特点

  • 在组件创建前调用,只执行一次
  • 返回的对象被所有实例共享,节省内存
  • 返回值会被缓存

二、static defaultProps(类组件)

ES6 类组件中使用静态属性 defaultProps 来设置默认值。虽然功能与 getDefaultProps 相同,但语法更清晰。

class Button extends React.Component {
  static defaultProps = {
    text: 'Click me',
    type: 'primary',
  }

  render() {
    return <button className={this.props.type}>{this.props.text}</button>
  }
}

或者在类定义后赋值:

class Button extends React.Component {
  render() {
    return <button className={this.props.type}>{this.props.text}</button>
  }
}

Button.defaultProps = {
  text: 'Click me',
  type: 'primary',
}

三、函数组件的默认参数(现代推荐)

现代 React 开发使用函数组件,通过函数参数的默认值或解构赋值来设置 props 的默认值。这是目前最推荐的做法。

解构时直接设置默认值

function Button({ text = 'Click me', type = 'primary' }) {
  return <button className={type}>{text}</button>
}

整个 props 对象设置默认值

function Card({ title, description = 'No description' }) {
  return (
    <div>
      <h2>{title}</h2>
      <p>{description}</p>
    </div>
  )
}

与 TypeScript 的配合

interface ButtonProps {
  text?: string
  type?: 'primary' | 'secondary'
}

function Button({ text = 'Click me', type = 'primary' }: ButtonProps) {
  return <button className={type}>{text}</button>
}

四、对比与选择

方式适用场景优点缺点
getDefaultPropsES5 老项目与老语法一致已废弃,不推荐新项目使用
static defaultProps类组件清晰可见,与类绑定需要额外声明,仍然需要 PropTypes 或 TypeScript
函数组件默认参数新项目、现代代码简洁、原生 JS 语法、易于类型推导只适用于函数组件

记住这一条:在新项目中总是优先使用函数组件和默认参数语法。如果必须使用类组件,用 static defaultProps。ES5 的 getDefaultProps 只在维护老项目时保留。

On this page