Skip to content

警告: Support for defaultProps 将是 移除从 函数组件

错误信息

                Support for defaultProps 将是 移除从 函数组件 in future major 发布.
              

快速摘要

你设置 `组件.defaultProps` on 函数组件, 哪个是 deprecated. Use JavaScript 默认参数相反.

为什么发生

  • Used MyComponent.defaultProps = { ... } on 函数组件

  • 复制模式从 类组件到 函数组件

最小示例

✗ 错误代码
function Button({ label }) {
  return <button>{label}</button>;
}
Button.defaultProps = { label: "Click" }; // Deprecated!
✓ 修复代码
function Button({ label = "Click" }) {
  return <button>{label}</button>;
}

默认参数 in 函数 signature 是 modern 方式到 设置默认 prop 值 for 函数组件.

如何诊断

  • 搜索 for .defaultProps in codebase

  • 检查如果它's applied 到函数组件

如何修复

  • Use 默认参数: 函数 MyComponent({ prop = defaultValue })

  • Destructure 使用 defaults: 函数 MyComponent({ prop = '默认' })

如何预防

  • 总是 use 默认参数 for 函数组件 defaults

  • 仅 use defaultProps for 类组件 (也 deprecated)

相关资源

相关术语

相关课程

  • Props

    学习 modern 默认 prop 模式.

← 返回语言