前端/移动开发面试题更新 2026-08-05

请解释 React 中 getDefaultProps 的含义及其功能。

前端/移动开发技术原理React

考察说明

考查对 React 组件默认属性机制的理解。

回答思路

  1. 【回答框架 1】getDefaultProps 是 React 早期版本(如 React.createClass)中用于定义组件默认 props 的方法,返回一个对象,组件未传入相应 prop 时使用默认值。
  2. 【回答框架 2】在 ES6 class 组件中,通过静态属性 defaultProps 实现;函数组件使用函数组件名.defaultProps。
  3. 【回答框架 3】默认 props 在组件实例化时合并,组件内可通过 this.props 读取,且默认值仅当父组件未传递该 prop 时生效。
  4. 【关键点 1】getDefaultProps 用于设置组件默认 props。
  5. 【关键点 2】多个实例共享同一默认 props 对象,避免被修改。
  6. 【关键点 3】ES6 组件使用 defaultProps 静态属性替代。
  7. 【易错点 1】误以为 getDefaultProps 是当前 React 推荐用法,实际已废弃。
  8. 【易错点 2】容易忽略默认 props 对象是共享的,修改可能影响其他实例。