首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在TypeScript中使用对象解构为构造函数中的类级属性赋值?

问如何在TypeScript中使用对象解构为构造函数中的类级属性赋值?
EN

Stack Overflow用户
提问于 2020-06-23 19:34:45
回答 1查看 138关注 0票数 1

我正在为我的react项目使用Typescript。因此,我在构造函数中传递道具。我想在构造函数中中断"props“,并将其赋给类级变量。

这是我的代码-

代码语言:javascript
复制
abstract class IProps{
abstract type:'text'|'checkbox'|'radio';
abstract value?: any;
abstract name?: string;
abstract id?:string;
abstract onClick?: ((event: React.MouseEvent<HTMLInputElement, MouseEvent>) => void);
abstract onChange?:((val: any) => void);
abstract classnames: string;
abstract placeholder?: any;
}
interface InputProps extends IProps{
    isvalid?: boolean;
}

export class Input extends Component<InputProps>{

    isvalid: boolean|undefined=true;
iProps: IProps|null = null;

constructor(props: InputProps){
    super(props);
    console.log(this.props);
    const {isvalid, ...iProps} = this.props;
    this.isvalid = isvalid;
    this.iProps = iProps;        
    }
}

构造函数中的这些语句适用于我。

代码语言:javascript
复制
 const {isvalid, ...iProps} = this.props;
    this.isvalid = isvalid;
    this.iProps = iProps; 

但是我想在不使用const语句的情况下赋值。我想做这样的事情-

代码语言:javascript
复制
{isvalid: this.isvalid, ...iProps: this.iProps} = this.props;

如何像这样赋值?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-23 19:36:26

因为它以{开头,所以您需要通过将其包装在()中来告诉解析器它是一个表达式,而不是块的开头

代码语言:javascript
复制
({isvalid: this.isvalid, ...this.iProps} = this.props);

Playground example -

代码语言:javascript
复制
class Example extends React.Component<InputProps> {
  isvalid: boolean;
  iProps: Partial<InputProps> = {}; // <=== Without the `= {}`, the assignment in
                                    // the constructor gets what seems to be an
                                    // erroneous error about trying to use iProps
                                    // before it's initialized
  constructor(props: InputProps){
    super(props);
    ({isvalid: this.isvalid, ...this.iProps} = this.props);
  }
}

这是一个简化的JavaScript版本,你可以在这里运行,所以:

​

代码语言:javascript
复制
class Example {
    constructor(props){
        ({isvalid: this.isvalid, ...this.iProps} = props);
    }
}
console.log(new Example({isvalid: false, a: 42, b: "example"}));

​

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62533740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档