我無法為 Typescript React Props 獲取正確的語法。我有一群人,每個人可能有 0 輛汽車。我有一個包含所有人的人員容器,每個人都有一個可能包含汽車的汽車容器,以及將在汽車容器內的汽車組件。
無論如何,我需要有汽車的容器,因為我將添加編輯按鈕,這些按鈕會將汽車添加到人。
我將從上到下添加我的代碼:
人物切片:
export interface PersonState {
id?: number;
firstname?: string;
lastname?: string;
email?: string;
created_at?: any;
updated_at?: any;
cars?: [];
}
人.tsx:
function People() {
const people = useAppSelector(selectPerson); //person is of type interface PersonState[]
let contents;
contents = <><div className="personcontainer">
{people && people.length > 0 && people.map(person => {
return <div key={person.id}>
<Person
dispatch={dispatch}
person={person}
toggleEditForm={() => toggleEditForm(person.id)}
personToEdit={personToEdit}
submitEdit={submitEdit}
/>
</div>
})}
</div></>
});
}
這是我開始遇到問題的地方-
人.tsx:
interface PersonProps {
dispatch: Dispatch<any>;
person: PersonState;
toggleEditForm: () => void;
submitEdit: any;
personToEdit: number;
}
function Person(props: PersonProps) {
return (
<div className="person">
<Cars cars={props.person.cars}/> //cars error: type [] | undefined not assignable to car[]
</div>
);
}
汽車.tsx:
import {car, Car} from './car';
interface cars {
cars: car[];
}
function Cars (props: cars) {
return (
<div className="carcontainer">
<h2>cars container</h2>
{props.cars && props.cars.map((carobj: car) => {
<Car car={carobj} key={}/> //car error: Type '{ car: car; key: any; }' is not assignable to type 'IntrinsicAttributes & car'.
})}
</div>
)
}
export default Cars;
最后是 car.tsx:
export interface car {
year: number,
make:string,
model: string,
price: number,
person_id: number,
}
export function Car (props: car) {
return (
<div className="carcontainer">
<h3>
{props.year} {props.make} {props.model} {props.price}
</h3>
</div>
)
}
所以我有兩個錯誤,一個在 person.tsx 中,一個在 cars.tsx 中,我在代碼中添加為注釋。
我已經閱讀了十幾個關于此的問題,但我仍然非常困惑。我究竟做錯了什么?
謝謝
uj5u.com熱心網友回復:
這兩個問題的修復都在cars.tsx.
import {car, Car} from './car';
interface cars {
cars?: car[]; // make this optional since the data from PeopleState is optional
}
function Cars (props: cars) {
return (
<div className="carcontainer">
<h2>cars container</h2>
{props.cars && props.cars.map((carobj: car) => {
<Car {...carobj} key={}/> // spread carobj into the component
})}
</div>
)
}
export default Cars;
uj5u.com熱心網友回復:
<Cars cars={props.person.cars}/> //cars error: type [] | undefined not assignable to car[]
這并不是真正的錯誤。您特別寫道:
cars?: [];
這意味著,“我可能不知道這個人在哪里有車。” 如果你不這樣做,顯然你不能渲染汽車串列。
也許你真的不知道,在這種情況下,你的代碼應該是這樣的:
{ props.person.cars?
<Cars cars={props.person.cars}/>
: <span>I do not know if he has cars</span> }
或者,您確實了解汽車,但您可能知道沒有汽車,在這種情況下,您應該這樣說:
cars: [];
在第二個問題中,您實際上需要給它一個密鑰:
{props.cars && props.cars.map((carobj: car, idx) =>
<Car car={carobj} key={idx}/> )}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442535.html
上一篇:我如何設定屬性的值
下一篇:如何輸入:const[{dataContents,isLoading,isError},doFetch]=useFetchData();
