为什么用require("../images/restaurants/sea.jpeg")可以导入图片,require(this.props.image)却不能

Why can image be imported with require("../images/restaurants/sea.jpeg"), but not with require(this.props.image)

在我的 create-react-app 项目中,我正在构建一个带有图像的 React 组件。 我想通过 component-属性 (或 -state)传递确切的图像位置。 在我的组件中,我正在使用 require,就像这样:

<Image
      height={"100px"}
      borderRadius={8}
      src={require(this.props.image)}
      alt="logo"
    /> 

这给出了这个错误:

Error: Cannot find module '../images/restaurants/sea.jpeg'

webpackEmptyContext
src/components sync:2

但是,当我将通过 属性 传递的确切值硬编码为 require 时,它​​确实有效!

<Image
      height={"100px"}
      borderRadius={8}
      src={require("../images/restaurants/sea.jpeg")}
      alt="logo"
    />

为什么这会如此违反直觉?最好的解决方法是什么?

Webpack 需要在打包时了解该文件 - 否则它不会包含它(它会试图降低您的捆绑包的大小)。

如果您将文件路径作为 prop 传递,它在打包时不知道它 - 它只在运行时知道它。

传递 base64 编码图像的建议解决方案是一个很好的解决方案 - 或者您可以将 url 传递到公共托管图像?

如果图像集是固定的并且在编译时已知,您可以通过多种方式实现您想要的效果。为此,您必须将所有此类图像放在一个文件夹中,并使用 webpack.ContextReplacementPlugin 您可以为该文件夹创建一个 webpack 上下文。然后,每当您需要该图像时,您必须使用此语法 require("images/restaurants/" + this.props.image) 假设 webpack 上下文是为 images/restaurants 创建的并且 this.props.image 仅包含文件名。