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.
}
}
我从我的react组件中调用上述类,如下所示。
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类传递数组对象时,我如何实现同样的工作。在不修改我的Cars类的情况下,如何通过使用任何for循环或map来设置Cars类中的每个对象?我正在使用react hooks,Redux,RxJS和typecript。
我对react.js、hooks和typeciprt都很陌生,如果有任何帮助,我将感激不尽。
[
{
carType: "4wheeler";
carColors: ["red", "green"];
},
{
carType: "2wheeler";
carColors: ["pink", "yellow"];
}
]
我想你的 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类的对象,所以每一个Cars:const car = new Cars()
指的是一辆车,但CarList有一个cars属性。