Warm tip: This article is reproduced from serverfault.com, please click

reactjs-尝试从CRA应用程序中的json路径加载图像的问题

(reactjs - Issue trying to load image from json path in CRA app)

发布于 2020-11-29 13:04:29

我无法从src/assets/image我的CRA应用程序中加载图像我想避免将这些图像放在我的公用文件夹中,但是由于某些原因,这似乎是显示它们的唯一方法。

我有一个homepageinfo.ts带有路径的json文件

export const homepageinfo: homepageinfoType = {
  ...
  hero_portrait: "testimg.jpg",
};

一个dataClient利用函数getHomePageInfo导入json文件的util函数文件

export const getHomePageInfo = () => {
  return homepageinfo;
};

和另一个文件 HomeTitle.tsx

import React from "react";
import { Grid, Header, Image, Segment } from "semantic-ui-react";
import { getHomePageInfo } from "utils/dataClient";

export const HomeTitle = () => {
  let homepageinfo = getHomePageInfo();

  return (
    <Grid columns={2}>
      ...
      <Grid.Column
        only="tablet computer"
        verticalAlign="bottom"
        textAlign="right"
      >
        {console.log(require("assets/image/" + homepageinfo.hero_portrait))}
        <Image as="img"
          className="img_portrait"
          spaced={"left"}
          src={require("assets/image/" + homepageinfo.hero_portrait)}
        />
      </Grid.Column>
    </Grid>
  );
};

console.log能够返回asset / image / homepageinfo.hero_portrait的值,但是在实际的Image组件中它仍然显示为空白。

空白组件的图像和Firefox的控制台输出

如果我将图像移动到公用文件夹,则可以显示该图像,但我不想将这些图像放在公用文件夹中。

Questioner
nullmage
Viewed
11
Vitalii 2020-11-29 21:46:18

你需要default从返回的结果require()

这通常会为你处理时import的语句用来代替require()

import React from "react";
import { Grid, Header, Image, Segment } from "semantic-ui-react";
import { getHomePageInfo } from "utils/dataClient";

export const HomeTitle = () => {
  let homepageinfo = getHomePageInfo();
  let imageUrl;
  try {
    const res = require("assets/image/" + homepageinfo.hero_portrait);
    console.log(res);
    imageUrl = res.default;
  } catch () {
    imageUrl = ''; // file not found
  }

  return (
    <Grid columns={2}>
      ...
      <Grid.Column
        only="tablet computer"
        verticalAlign="bottom"
        textAlign="right"
      >
        <Image as="img"
          className="img_portrait"
          spaced={"left"}
          src={imageUrl}
        />
      </Grid.Column>
    </Grid>
  );
};

如果找不到文件,UPDATED require()可能会失败。

因此,我建议使用像这样的import文档建议

homepageinfo.ts

import testImg from './assets/image/testimg.jpg';

export const homepageinfo: homepageinfoType = {
  ...
  hero_portrait: testImg,
};

这样,所有图像将在构建期间解析为路径,homepageinfo.hero_portrait并将包含结果URL