如果 React 组件的属性没有传值,它的默认值是什么?

0 阅读1分钟

在 React 中,组件的 props 没有传值时,默认是 undefined。

例如:

function Button(props) {
  console.log(props.size);
  return <button>按钮</button>;
}

<Button />

此时:

props.size === undefined // true

如果你想设置默认值

现代 React 推荐直接使用 参数默认值:

function Button({ size = 'medium' }) {
  return <button>{size}</button>;
}

不传:

<Button />

相当于:

size === 'medium'

传入:

<Button size="large" />

则使用:

size === 'large'

注意 null

默认参数只对 undefined 生效:

function Button({ size = 'medium' }) {
  console.log(size);
}

<Button />                  // "medium"
<Button size={undefined} /> // "medium"
<Button size={null} />      // null

所以可以简单记:

React props 不传 → undefined;如果设置了默认值 → undefined 会触发默认值,但 null 不会。

另外,如果你说的是 React 类组件以前的 defaultProps,我也可以给你讲一下它和函数组件默认参数的区别。