簡體   English   中英

如何在 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" />而不是聲明 function。

  1. 現在,使用image: () => <Img type="right-arrow" /> ,您將不得不調用 function 來渲染組件。
<>
  {config.emailAddress.image()}
</>

我認為第一種方法總是更容易。

這也應該可以幫助您理解為什么可以如此輕松地加載 SVG。

SVG 可以作為 React 代碼中的 React 組件直接導入和使用。 圖像不會作為單獨的文件加載,而是沿着 HTML 呈現。

有關實現詳細信息,請參閱此 stackoverflow 答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM