我遇到了一个相当奇怪的问题。我正在使用 TypeScript 和 Preact 创建一个 Button 组件。我使用 TypeScript 接口(interface)进行 Prop 验证,本质上是使用常量变量作为“默认” Prop 。然后使用 Object.assign 应用这些 props 并将其传递给 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: {...} }
.
感谢您的阅读,感谢您提供的任何帮助!
最佳答案
您想要将 Prop 和默认 Prop 合并到一个新对象中。所以你可以这样做
super(Object.assign({}, ButtonPropsDefaults, props)) or
super({...ButtonPropsDefaults, ...props})
关于javascript - Object.assign 在构造函数之外被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54687572/