【问题标题】:How to pass array of objects to Class in Typescript如何将对象数组传递给Typescript中的类
【发布时间】:2020-08-26 11:54:45
【问题描述】:
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.
    }
}

我正在从我的反应组件中调用上述类,如下所示。

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

我的html如下

 const [myUseStateObjForCars, setMyUseStateObjForCars] = useState(0);
 const [myUseStateArrayForCars, setMyUseStateArrayForCars] = useState(0);

<input onChange={e=> setMyUseStateObjForCars(e.target.value)}
<input onChange={e=> setMyUseStateArrayForCars(e.target.value)}

当我将 Cars 作为单个对象时,这可以正常工作。 当我必须将对象数组传递给我的 Car 类时,我怎样才能达到同样的效果。不通过使用任何 for 循环或映射来修改我的类 Cars 来设置我的 Cars 类中的每个对象? 我正在使用 react hooks、Redux、RxJS 和 typescript。

这是可能的还是我在这里做错了什么? 对此的任何帮助将不胜感激,因为我是 react.js 、 hooks 和 typeciprt 的新手。

[
    {
        carType: "4wheeler";
        carColors: ["red", "green"];        
    },
    {
        carType: "2wheeler";
        carColors: ["pink", "yellow"];  
    }
]

【问题讨论】:

  • 打字稿 1.8 / 2.0?当然?我们在 V3.9。垃圾邮件标签通常在 SO 上不受欢迎。如果这些不是过时的标签,您可能会收集到几个反对票。

标签: reactjs typescript react-hooks typescript2.0 typescript1.8


【解决方案1】:

我认为你的class Cars 不应该实现ICars,但如果你想实现它试试这个:

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

// Add an extra class
export class CarList {
   private cars: Partial<Cars[]>;

   public constructor (cars: <Cars[]>) {
      this.cars = [];
   }

   public addCar (car: ICars) {
      this.cars.push(new Cars(carType: "Some value", ["red", "yellow"]));
   }
}

请记住,您可以实例化 Cars 类的一个对象,因此每个: const car = new Cars() 指的是单辆车,但 CarList 有一个 cars 属性

【讨论】:

  • 感谢您的回复....我想知道是否有其他方法无需添加额外的类,我可以使用相同的>>(导出类 Cars 实现 ICars)来实现。班级?喜欢使用一些 for 循环或 map 函数来帮助我在汽车类中设置对象?
  • 如果没有添加额外的类,则不需要实现ICars export interface ICars{ carType?: string; carColors: string[]; } export class Cars { private cars: Partial&lt;ICars[]&gt;; constructor(data: Partial&lt;ICars[]&gt;){ this.cars = data.length &gt; 0 ? [...data] : []; } public addCars (car: ICars) { this.cars.push({...car}); } }
  • 导出接口 ICars{ car​​Type?: string;汽车颜色:字符串[]; } 出口类汽车 { 私家车:Partial;构造函数(数据:部分){ this.cars = data.length > 0 ? [...数据] : []; } 公共 addCars(汽车:ICars){ this.cars.push({...car});请记住,您可以实例化 Cars 类的 Object,因此每个 const car = new Cars() 都指向一辆汽车,但 CarList 有一个 cars 属性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2016-06-06
  • 2021-11-26
  • 1970-01-01
相关资源
最近更新 更多