reactjs - 如何在 React + TypeScript 中设置 Prop 类型

标签 reactjs typescript

我学习了 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/

相关文章:

javascript - React 渲染毫无意义的 div 打破了我的 flexbox 风格

Angular 无法编译 Typescript 的映射类型修饰符

javascript - 从许多编译为 AMD 模块的 TypeScript 类创建单个 AMD 模块?

javascript - 访问对象内部的数组

javascript - CRA 中是否有在 URL 末尾添加斜杠的设置?

node.js - express-http-proxy代理来响应js应用,但没有任何内容

javascript - JSON 文件仅在函数中加载,但一旦完成,加载的数据就会在 React 中消失

angularjs - typescript : AngularJS retrieving a result object

typescript - 如何使声明的函数根据用法自动推断类型?

reactjs - 使用 typescript react 在构造函数中声明一个属性