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