将在 React 组件中解构的道具默认值的影响
Effects of default value for props that will be destructured in a React Component
假设我有一个像这样的简单组件(假设所有内容都正确导入):
const SpecialButton = (props) => {
const { css, ...rest } = props;
return (
<Button
className={`special-btn ${css}`}
{...rest}
>
Click here
</Button>
);
};
SpecialButton.defaultProps = {
css: '',
rest: {}
};
SpecialButton.propTypes = {
css: PropTypes.string,
rest: PropTypes.object
}
我正在为其余道具设置默认值 {}
,我还使用对象解构将其传递给 Button 组件。
所以,假设使用 SpecialButton 的人除了 css 道具之外没有传递任何其他东西,我的问题是:
- 由于 {} 是对象 class 的一个实例,当我使用
...
时,它是否将对象的所有属性转储到按钮组件中?
- rest props不指定默认值有什么问题吗?
- 请问各位有什么更好的处理方法的建议吗?
为了完整性,我正在添加道具类型和默认道具,但我不能 100% 确定是否需要。
谢谢。
我假设您正在从 'props'.
解构 css
和 rest params
const { css, ...rest } = props;
现在 rest
不是 属性 道具对象,解构后它具有除 css 属性.
之外的所有道具属性
编辑:实际上有一个 "effect" 将 "rest" prop 添加到 defaultProps,这将导致 rest 参数包含 rest: {}
属性 和依次将其传递给本例中的 Button 组件。
回答您的问题
Since {} is an instance of the Object class, when I use the ... does
it dump all the properties of the Object into the Button component?
不,使用扩展运算符仅提供用户定义的键。所以你不会找到 Object.
的任何属性
Is there any problem in not specifying a default value for the rest
props?
正如我所说,为其余参数分配默认值不会有任何效果。
Do you guys have a better suggestion about how to handle this case?
如果您将其余参数传递给子项,则不必为将出现在其余参数中的属性设置默认道具。
这很好。
SpecialButton.defaultProps = {
css: '',
};
SpecialButton.propTypes = {
css: PropTypes.string,
}
当你需要将 proptypes 应用到对象时,也使用 PropTypes.shape 而不是 PropTypes.object。
假设我有一个像这样的简单组件(假设所有内容都正确导入):
const SpecialButton = (props) => {
const { css, ...rest } = props;
return (
<Button
className={`special-btn ${css}`}
{...rest}
>
Click here
</Button>
);
};
SpecialButton.defaultProps = {
css: '',
rest: {}
};
SpecialButton.propTypes = {
css: PropTypes.string,
rest: PropTypes.object
}
我正在为其余道具设置默认值 {}
,我还使用对象解构将其传递给 Button 组件。
所以,假设使用 SpecialButton 的人除了 css 道具之外没有传递任何其他东西,我的问题是:
- 由于 {} 是对象 class 的一个实例,当我使用
...
时,它是否将对象的所有属性转储到按钮组件中? - rest props不指定默认值有什么问题吗?
- 请问各位有什么更好的处理方法的建议吗?
为了完整性,我正在添加道具类型和默认道具,但我不能 100% 确定是否需要。
谢谢。
我假设您正在从 'props'.
解构css
和 rest params
const { css, ...rest } = props;
现在 rest
不是 属性 道具对象,解构后它具有除 css 属性.
编辑:实际上有一个 "effect" 将 "rest" prop 添加到 defaultProps,这将导致 rest 参数包含 rest: {}
属性 和依次将其传递给本例中的 Button 组件。
回答您的问题
Since {} is an instance of the Object class, when I use the ... does it dump all the properties of the Object into the Button component?
不,使用扩展运算符仅提供用户定义的键。所以你不会找到 Object.
的任何属性Is there any problem in not specifying a default value for the rest props?
正如我所说,为其余参数分配默认值不会有任何效果。
Do you guys have a better suggestion about how to handle this case?
如果您将其余参数传递给子项,则不必为将出现在其余参数中的属性设置默认道具。
这很好。
SpecialButton.defaultProps = {
css: '',
};
SpecialButton.propTypes = {
css: PropTypes.string,
}
当你需要将 proptypes 应用到对象时,也使用 PropTypes.shape 而不是 PropTypes.object。