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.
}
}
And I am calling the above class from my react component as below.
const carTemplate: Cars = new Cars({
carType: myUseStateObjForCars,
carColors: myUseStateArrayForCars,
})
My html is as follows
const [myUseStateObjForCars, setMyUseStateObjForCars] = useState(0);
const [myUseStateArrayForCars, setMyUseStateArrayForCars] = useState(0);
<input onChange={e=> setMyUseStateObjForCars(e.target.value)}
<input onChange={e=> setMyUseStateArrayForCars(e.target.value)}
This works fine when I have an Cars as a single object. How can I achieve the same when I have to pass array of object to my Car class. Without modifying my class Cars by using any for loop or map to set every object inside my Cars class? I am using react hooks,Redux, RxJS and typescript.
Is this possible or am I doing something wrong here? Any help on this would be appreciated as I am new to react.js, hooks and typesciprt.
[
{
carType: "4wheeler";
carColors: ["red", "green"];
},
{
carType: "2wheeler";
carColors: ["pink", "yellow"];
}
]
I think your class Cars
shouldnt implement ICars
, but if you want to implement it try this:
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"]));
}
}
Remember you can instantiate an Object of the class Cars so each: const car = new Cars()
refers to a single car, but the CarList has a cars property
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.