Reactjs 如何在Typescript中将对象数组传递给类

Reactjs 如何在Typescript中将对象数组传递给类,reactjs,typescript,react-hooks,typescript2.0,typescript1.8,Reactjs,Typescript,React Hooks,Typescript2.0,Typescript1.8,我从我的react组件调用上面的类,如下所示 export interface ICars{ carType?: string; carColors: string[]; } export class Cars implements ICars{ carType?: string; carColors: string[]; constructor(data?: ICars){ //here code is present to set

我从我的react组件调用上面的类,如下所示

export interface ICars{
    carType?: string;
    carColors: string[];
}

export class Cars implements ICars{
    carType?: string;
    carColors: string[];

    constructor(data?: ICars){
        //here code is present to set the carType and car Color parameters.
    }
}
我的html如下

const carTemplate: Cars = new  Cars({
    carType: myUseStateObjForCars,
    carColors: myUseStateArrayForCars,
})

我认为你的
级车
不应该实施
ICars
,但如果你想实施它,请尝试以下方法:

导出接口ICars{
carType?:字符串;
carColors:string[];
}
出口级汽车实施ICars{
carType?:字符串;
carColors:string[];
建造商(数据?:ICars){
//这里提供了设置carType和car Color参数的代码。
}
}
//添加一个额外的类
出口级卡里斯特{
私家车:部分;
公共建筑商(汽车:){
这个.cars=[];
}
公共addCar(car:ICars){
this.cars.push(新车(carType:“Some value”[“red”,“yellow”]);
}
}
请记住,您可以实例化Cars类的一个对象,以便每个:
const car=新车()

指的是一辆车,但CarList有一个cars属性

谢谢您的回复……我想知道,在不添加额外等级的情况下,是否有其他方法可以使用相同的>>(export class cars实现ICars)。班比如使用一些for循环或映射函数来帮助我设置cars类内部的对象?如果没有添加额外的类,那么您就不需要实现ICars
export接口ICars{carType?:string;carColors:string[];}export Class cars{private cars:Partial;constructor(数据:Partial){this.cars=data.length>0?[…data]:[];}公共addCars(car:ICars){this.cars.push({…car});}
export-interface-ICars{carType?:string;carColors:string[];}导出类汽车{私家车:部分;构造函数(数据:部分){this.cars=data.length>0?[…data]:[];}公共addCars(car:ICars){this.cars.push({…car});}}记住可以实例化cars类的一个对象,这样每个const car=new cars()指的是一辆车,但CarList有一个cars Property TypeScript 1.8/2.0?确定吗?我们是V3.9。因此,通常不欢迎使用垃圾邮件标签。如果这些标签不是过时的,您可能会收到几张反对票。
 const [myUseStateObjForCars, setMyUseStateObjForCars] = useState(0);
 const [myUseStateArrayForCars, setMyUseStateArrayForCars] = useState(0);

<input onChange={e=> setMyUseStateObjForCars(e.target.value)}
<input onChange={e=> setMyUseStateArrayForCars(e.target.value)}
[
    {
        carType: "4wheeler";
        carColors: ["red", "green"];        
    },
    {
        carType: "2wheeler";
        carColors: ["pink", "yellow"];  
    }
]