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

问题描述 投票:0回答:1

我有一个相当奇怪的问题。我正在使用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>,则render函数中的console.log语句将为{ color: "primary", children: {...} }

感谢您阅读,我感谢您提供的任何帮助!

javascript typescript preact
1个回答
1
投票

您希望将道具和默认道具合并到一个新对象中。所以你可以做到

super(Object.assign({}, ButtonPropsDefaults, props)) or
super({...ButtonPropsDefaults, ...props})
© www.soinside.com 2019 - 2024. All rights reserved.