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

标签 javascript reactjs image react-native arrow-functions

我在 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" />而不是声明一个函数。

  • 现在,与 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.

    参见this stackoverflow answer了解实现细节。

    关于javascript - 如何在 React 中使用导入的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65942303/

    相关文章:

    javascript - 为什么事件处理程序能够劫持我对 eval 的直接调用?

    javascript - 使用对象字面量创建新对象

    javascript - 如何在外部函数中使用setState?

    html - Internet Explorer 和 Google Chrome 的内容显示方式不同

    javascript - 单击 Bootstrap 模式获取 src 值

    c# - 有没有浏览器会自动添加内联CSS的场景?

    javascript - 如何在 defaultProps React.Component 类语法中使用 'this' ?

    reactjs - Jest/React 测试库 : Is it Possible to Spy on and Wait GraphQL Queries as with Cypress?

    javascript - 使用 javascript 根据下拉列表更改图像。

    java - 在java中使用缩放来提高jpeg图像质量