如何在 React 中使用导入的图像?

How to use an imported image in React?

我使用 React 编程的时间很短,我对如何进行有一些疑问。 我有一个组件将导入的 svg 显示为图像。

import Arrow from '../arrow.svg';


    if (!isChecked) {

      config.email = {
        clickable: true,
        image: Arrow,
        onClick: () =>
          inProfile
            ? dispatch(notification(CHANGE_STATUS))
            : browserHistory.push(/checkOut),
      };
    }


现在我想用从外部库导入的图像替换我项目中的图像,该图像呈现如下


<Img type="right-arrow" />

这是一个正在我的代码中运行的示例



  renderImage() {
    return <Img type="right-arrow" />;
  }

  render() {

    return(
      {this.renderHeader}
      {this.renderTitle}
      {this.renderBody}
      {this.renderImage}
    );

  }

如何使用这个新导入的组件来代替以前使用的图像?

我尝试了几种方法,但无法渲染它。

我最后尝试的是以下内容

import Image from '@market/image-market';


    if (!isChecked) {

      config.email = {
        clickable: true,
        image: <Img type="right-arrow" />
        onClick: () =>
          inProfile
            ? dispatch(notification(CHANGE_STATUS))
            : browserHistory.push(/checkOut),
      };
    }



我不知道如何在此结构中使用它。如果有人能看到我的错误。非常感谢您的宝贵时间和提前帮助

我认为您对引擎盖下发生的事情有点困惑。

  1. 如果config.emailAddress.image这样使用
<>
  {config.emailAddress.image}
</>

你应该只传递 image: <Img type="right-arrow" /> 而不是声明一个函数。

  1. 现在,使用 image: () => <Img type="right-arrow" />,您将必须调用函数来渲染组件。
<>
  {config.emailAddress.image()}
</>

我认为第一种方法总是更容易。

这应该也能帮助您理解为什么 SVG 可以如此轻松地加载。

SVGs can be imported and used directly as a React component in your React code. The image is not loaded as a separate file, instead, it’s rendered along the HTML.

有关实施细节,请参阅