由于条件渲染中的道具而导致打字稿错误

时间:2020-03-01 22:20:53

标签: reactjs typescript

有一个简单的带组件返回条件语句:

let content = movies.length > 0 ? movies.map((movie, i) => <MovieCard key={i} movie={movie} />) : null;

打字稿在“电影”道具上显示错误:

TS2322: Type '{ key: number; movie: object; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
        Property 'movie' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.
import React from "react";
import { Link } from 'react-router-dom';


const MovieCard: React.FC = ({ movie }) => {

    return (
        <div className="col-md-3 mb-5">
            <div className="card card-body bg-dark text-center h-100">
                <img className="w-100 mb-2" src={movie.Poster} alt="Movie Cover" />
                <h5 className="text-light card-title">
                    {movie.Title} - {movie.Year}
                </h5>
                <Link className="btn btn-primary" to={'/movie/' + movie.imdbID}>
                    Movie Details
                    <i className="fas fa-chevron-right" />
                </Link>
            </div>
        </div>
    );
};

export default MovieCard;

请帮助我了解我错过了什么。我是TS的新手。

1 个答案:

答案 0 :(得分:1)

您需要为MovieCard功能组件定义道具类型。


import React from "react";
import { Link } from 'react-router-dom';

export interface Movie {
  imdbID: number,
  Title: string,
  Year: string
}

export interface Props {
   movie: Movie
}

const MovieCard: React.FC<Props> = ({ movie }) => {

    return (
        <div className="col-md-3 mb-5">
            <div className="card card-body bg-dark text-center h-100">
                <img className="w-100 mb-2" src={movie.Poster} alt="Movie Cover" />
                <h5 className="text-light card-title">
                    {movie.Title} - {movie.Year}
                </h5>
                <Link className="btn btn-primary" to={'/movie/' + movie.imdbID}>
                    Movie Details
                    <i className="fas fa-chevron-right" />
                </Link>
            </div>
        </div>
    );
};

export default MovieCard;

您可以查看此cheatsheet中的react-typescript