请说明React中getDefaultProps 的作用 ?
参考答案:
getDefaultProps
是 React 组件生命周期中的一个方法,它在组件实例化并创建新的 props 对象之前被调用。getDefaultProps
的主要作用是允许你为组件设置默认的 props。当组件没有接收到特定的 props 时,它会使用 getDefaultProps
中定义的默认值。
需要注意的是,getDefaultProps
已经被标记为过时,并在 React 15.5 版本中被移除。取而代之的是使用类属性(class properties)或默认参数(default parameters)来定义组件的默认 props。
使用类属性定义默认 props 的示例:
import React from 'react';
class MyComponent extends React.Component {
static defaultProps = {
prop1: 'defaultValue1',
prop2: 'defaultValue2'
}
render() {
return (
<div>
{this.props.prop1}
{this.props.prop2}
</div>
);
}
}
export default MyComponent;
使用默认参数定义默认 props 的示例:
import React from 'react';
function MyComponent({ prop1 = 'defaultValue1', prop2 = 'defaultValue2' }) {
return (
<div>
{prop1}
{prop2}
</div>
);
}
export default MyComponent;
在上述示例中,如果在使用 MyComponent
时没有提供 prop1
或 prop2
,那么它们将分别默认为 'defaultValue1'
和 'defaultValue2'
。