1

我正在为我的反应项目使用 Typescript。因此,我在构造函数中传递道具。我想打破构造函数中的“道具”并将其分配给类级变量。

这是我的代码 -

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;        
    }
}

构造函数中的这些语句对我有用。

 const {isvalid, ...iProps} = this.props;
    this.isvalid = isvalid;
    this.iProps = iProps; 

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

{isvalid: this.isvalid, ...iProps: this.iProps} = this.props;

如何分配这样的值?

4

1 回答 1

2

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

({isvalid: this.isvalid, ...this.iProps} = this.props);

游乐场示例-

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 版本,您可以在 SO 上运行:

class Example {
    constructor(props){
        ({isvalid: this.isvalid, ...this.iProps} = props);
    }
}
console.log(new Example({isvalid: false, a: 42, b: "example"}));

于 2020-06-23T11:36:25.617 回答