我研究了反应 + 打字稿。我想设置组件功能道具类型。但我不知道如何设置。
这是代码。
interface MovieProps {
id: number;
title: string;
year: number;
}
function App() {
...
const movies: MovieProps[] = [
{ id:1, title: 'movie1', year: 2018 },
{ id:2, title: 'movie2', year: 2019 },
{ id:3, title: 'movie3', year: 2020 },
{ id:4, title: 'movie4', year: 2021 },
];
const renderMovies: JSX.Element[] = movies.map(movie => {
return (
<MovieCard key={ movie['id'] } movie={ movie } />
);
});
...
}
function MovieCard({ movie }: any) { <- this part
return (
<div className="movie">
<div className="movie-title">{ movie['title'] }</div>
<div className="movie-year">{ movie['year'] }</div>
</div>
);
};
我不想设置“任何”。我设置的类型是什么?
我会更改它,以便您将道具传递给您要使用的卡片,而不是将容器对象作为道具。这也使打字更简单。所以你可以这样做:
interface MovieProps {
id: number;
title: string;
year: number;
}
function App() {
...
const movies: MovieProps[] = [
{ id:1, title: 'movie1', year: 2018 },
{ id:2, title: 'movie2', year: 2019 },
{ id:3, title: 'movie3', year: 2020 },
{ id:4, title: 'movie4', year: 2021 },
];
const renderMovies: JSX.Element[] = movies.map(movie => {
return (
<MovieCard key={ movie.id } {...movie} />
);
});
...
}
function MovieCard({ title, year }: MovieProps) { <- this part
return (
<div className="movie">
<div className="movie-title">{ title }</div>
<div className="movie-year">{ year }</div>
</div>
);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句