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

で始まるため{、 でラップして、ブロックの開始ではなく式であることをパーサーに伝える必要があります()

({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);
  }
}

ここでSOで実行できる簡略化されたJavaScriptバージョンを次に示します。

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 に答える