我学习了 React + TypeScript。 我想设置组件功能 Prop 类型。 但是我不知道怎么设置。
这是代码。
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>
);
};
我不想设置“任何”。我设置什么类型?
最佳答案
我会更改它,以便您将 Prop 传递给您想要使用的卡片,而不是将容器对象作为 Prop 。这也使打字更简单。所以你可以这样做:
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>
);
};
关于reactjs - 如何在 React + TypeScript 中设置 Prop 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69105313/