javascript - Object.assign 在构造函数之外被覆盖
问题描述
我有一个相当奇怪的问题。我正在使用 TypeScript 和 Preact 创建一个 Button 组件。我使用 TypeScript 接口进行道具验证,本质上并使用常量变量作为“默认”道具。然后使用 Object.assign 应用道具并传递给 super。这是代码如下:
import classNames from "classnames";
import { Component, h } from "preact";
export interface ButtonProps {
color?: string;
type?: "primary" | "secondary";
}
const ButtonPropsDefaults: ButtonProps = {
color: "primary",
type: "primary",
};
export default class Button extends Component<PButtonProps> {
constructor(props: ButtonProps) {
// Logs { color: "primary", type: "primary" }
console.log(ButtonPropsDefaults);
super(Object.assign(ButtonPropsDefaults, props));
// Logs { color: "primary", type: "primary", children: {...} }
console.log(this.props);
}
public render() {
// Logs { children: {...} }
console.log(this.props);
const className = classNames({
"button": true,
[`button--color-${this.props.color}`]: !!this.props.color,
[`button--type-${this.props.type}`]: !!this.props.type,
});
return <button className={className}>{this.props.children}</button>;
}
}
注意 console.log 语句的结果。似乎值“恢复”回传递给构造函数的原始状态。因此,例如,如果我将组件用作<Button color="primary">Test</Button>
,则渲染函数中的 console.log 语句将是{ color: "primary", children: {...} }
。
感谢您的阅读,感谢您提供的任何帮助!
解决方案
您希望将道具和默认道具合并到一个新对象中。所以你可以做
super(Object.assign({}, ButtonPropsDefaults, props)) or
super({...ButtonPropsDefaults, ...props})
推荐阅读
- angular - StackBlitz 无法找到现有的 Angular SCSS 文件
- python - 'str' 对象没有属性 'find_all' 美丽的汤
- eclipse - 未能执行目标 com.google.appengine:appengine-maven-plugin:1.9.67:devserver
- python - How to create a recursive linked node insertion sort algorithm?
- java - Java minecraft 服务器无法在 linux 虚拟服务器机器上的 IPv4 上运行/侦听
- c - fprintf 不在 ^C 上写入,但在退出时写入
- php - 使用 Laravel 和 AJAX 搜索两个表时出错
- git - Git 排除某些提交和代码更改并将其他提交保持在最前面
- android - 带有地图意图的标记标签
- svm - 具有动态时间规整内核的 SVM