javascript - 占位符图像无法通过卡片正确加载 [ReactJs]

标签 javascript reactjs typescript syntax-error

所以我正在开发一个项目,该项目加载一个卡片列表,该列表从 API 获取数据,例如“Id、标题、URL 和缩略图 URL”。

如果 API 提供了缩略图 URL,卡片当前会加载图像,但如果未提供缩略图 URL,那么我想设置一个将在其位置显示的占位符图像。下图显示了当前如何使用 + 设置卡片而不使用缩略图 URL: enter image description here

如您所见,当前我已经设置了一个占位符图像,但由于某种原因,在占位符下加载了一个“错误”部分,这意味着图像部分中未提供任何图像。我想知道如何正式声明它是一个占位符图像以供使用,而无需将图像硬编码到卡中?

创建卡片的代码如下:

import React, { Component } from "react";
import "../help/HelpCardTwo.css";
import "../help/HelpList";
import Popup from "reactjs-popup";
import placeholder from "../help/placeholder.jpeg";

interface Props {
  id: string;
  url: string;
  title: string;
  thumbnail: string;
  deleteProduct: (id: any) => void;
  editProduct: (id: any, title: string, url: string, thumbnail: string) => void;
}

interface State {
  title: string;
  thumbnail: string;
  id: string;
  url: string;
  imageLoading?: boolean;
  tooManyRequests?: boolean;
}

export default class HelpCard extends Component<Props, State> {
  state = {
    url: "",
    id: "",
    title: "",
    imageLoading: true,
    tooManyRequests: false,
    thumbnail: ""
  };

  componentDidMount() {
    const { url, title, thumbnail } = this.props;
    const id = url.split("/")[url.split("/").length - 2];

    this.setState({
      url,
      id,
      title,
      thumbnail,
      imageLoading: true,
      tooManyRequests: false
    });
  }

  render() {
    const isThumbnail = this.state.thumbnail;
    const adminhelpcard = this.state;
    return (
      <React.Fragment>
        <article className="card card--2">
          <div className="card__img">
            {this.state.imageLoading ? <img src={placeholder} style={{ width: "100%", height: "100%" }}></img> : null}
            <img
              className="Sprite"
              onLoad={() => this.setState({ imageLoading: false })}
              onError={() => this.setState({ tooManyRequests: false })}
              src={this.state.thumbnail}
            />
          </div>

显示的代码仅适用于卡片的图像部分,不适用于卡片的其余部分。如果还需要任何其他信息,请告诉我,我将提供代码。

如何正式加载占位符图像,同时其下没有小错误方 block ?

提前谢谢

最佳答案

您正在尝试将二进制文件作为变量导入。为此,您需要检查您的 webpack 是否配置为具有正确的文件加载器。 你的 webpack.config.js 应该有这样的内容:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },
    ],
  },
};

关于javascript - 占位符图像无法通过卡片正确加载 [ReactJs],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58431696/

相关文章:

typescript - 如何使用 "path tuple"从嵌套属性中检索类型

angular - 如何解决这个问题,Angular 中的 "error TS2349: This expression is not callable"

javascript - 使用变量 Javascript 动态更改 gridTemplateColumns 重复值的任何方法

reactjs - 当状态依赖于 render 时,如何避免 render() 内的 setState()

reactjs - 如何在类中从react-router-dom v6获取参数值

javascript - 数组 slice() 给出的是引用而不是值

javascript - 将 div 移至特定 div 内,并在某些断点处再次移回

javascript - 如何在 JavaScript 中使用 livewire 发送两个参数?

javascript - 密码存储在谷歌浏览器的浏览器内存中

css - 我们可以将过滤器组件的输入字段替换为 Material UI 文本字段吗