我正在为我的react项目使用Typescript。因此,我在构造函数中传递道具。我想在构造函数中中断"props“,并将其赋给类级变量。
这是我的代码-
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;如何像这样赋值?
发布于 2020-06-23 19:36:26
因为它以{开头,所以您需要通过将其包装在()中来告诉解析器它是一个表达式,而不是块的开头
({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版本,你可以在这里运行,所以:
class Example {
constructor(props){
({isvalid: this.isvalid, ...this.iProps} = props);
}
}
console.log(new Example({isvalid: false, a: 42, b: "example"}));
https://stackoverflow.com/questions/62533740
复制相似问题