javascript - 将图像从 React 项目导入组件
问题描述
我正在使用 React 和 Typescript 构建一个应用程序。
我正在使用免费的 API 检索数据。我正在尝试为没有它们的对象使用默认图像。
这是我的项目的结构:
在movies.service.tsx
我获取数据并将从数据库中检索到的值分配给电影对象的属性图片(如果没有值,我想为其分配路径):default-poster.png
import * as img from '../images/default-poster.png';
console.log('img ', img);
const movieApiBaseUrl = "https://api.themoviedb.org/3";
const posterBaseUrl = "https://image.tmdb.org/t/p/w300";
export interface Movie {
id: number;
title: string;
rating: number;
description: string;
picture?: string;
date: string;
}
export function fetchMovies(): Promise<Movie[]> {
return fetch(
`${movieApiBaseUrl}/discover/movie?sort_by=year.desc&api_key=${process.env.REACT_APP_API_KEY}`
)
.then((res) => res.json())
.then((res) => mapResult(res.results))
.catch(() => {
return [];
});
}
// = movie has to be after const {} here
function mapResult(res: any[]): Movie[] {
return res.map((movie) => {
const {
id,
title,
vote_average,
overview,
poster_path,
date,
} = movie;
return {
id: id,
title: title,
rating: vote_average,
description: overview,
picture: poster_path ? `${posterBaseUrl}${poster_path}` : img,
date: date,
};
});
}
但是,Typescript 不允许我将 img 分配给图片属性。我还安慰了 img 值,它等于一个模块:
Module default: "data:image/png;base64,iVBORw0KGgoAAAA <...>" Symbol(Symbol.toStringTag): "Module" esModule: true __proto: Object
我需要将图像的路径分配给picture
属性,以便以后可以在MovieCards.tsx
组件中使用它们。
我应该改变什么?
谢谢!
解决方案
解决方案是将默认图像导入到movies.service.tsx
:
import noImage from '../images/no-image-available.png';
然后将变量noImage
作为三元运算符的第三个操作数传递:
picture: poster_path ? `${posterBaseUrl}${poster_path}` : noImage,
推荐阅读
- java - JAVA - 如何检测验证中的第一个零
- sql - 具有聚合函数的 SQL 子查询 - 寻找替代方法
- javascript - 使这个函数同步?
- python-3.x - Alexa 访问令牌有效范围
- java - 使用 JSON-B / Yasson 将 JSON 反序列化为多态 POJO
- c++ - 从文件资源管理器中选择图像后将图像放在屏幕上
- google-analytics - 当数据 api 达到限制时,youtube 分析 api 返回 Daily Limit Exceeded 错误
- c++ - 如何使用矩形绘制粗线?
- c++ - 检查一个类是否有可能重载的函数调用运算符
- python - 如何在 Python 中使用 imagemagick?