javascript - Object.assign 在构造函数之外被覆盖

标签 javascript typescript preact

我遇到了一个相当奇怪的问题。我正在使用 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/

相关文章:

javascript - 监听Chrome浏览器中的所有事件

javascript - 使用 "TypeError: $ is not a function"时我得到 "import * as jQuery"

javascript - 我可以在 Angular 中使用全局常量而不注入(inject) Controller 吗?

reactjs - 智能差异渲染原生如何进行预 react ?

reactjs - 用于生产的 Preact 和 Webpack

javascript - 清除各种间隔

javascript - 类型 'Date' 不可分配给类型 'Observable<Date>' - Angular 6+

typescript - ts 实例化一个作为参数传递的类

javascript - 如何减少 Angular 应用程序构建时间?

reactjs - 如何创建具有 HTMLAttributes 作为 Prop 的组件