Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
69 views
in Technique[技术] by (71.8m points)

javascript - How to use an imported image in React?

I have been programming in React for a short time and I have some doubts about how to proceed. I have a component that is displaying an imported svg as an image.

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


    if (!isChecked) {

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


Now I want to replace the image I have in my project with one imported from an external library that is rendered as follows


<Img type="right-arrow" />

Here is an example that is working in my code right now



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

  render() {

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

  }

How can I use this new imported component instead of the previously used image?

I have tried several ways but I can't get it to render.

the last thing I have tried is the following

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),
      };
    }



I don't see how I can use it within this structure. If someone could see my mistake. Thank you very much for your time and help in advance

question from:https://stackoverflow.com/questions/65942303/how-to-use-an-imported-image-in-react

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are just a little confused by what's happening under the hood.

  1. If the config.emailAddress.image is used like so
<>
  {config.emailAddress.image}
</>

You should just pass image: <Img type="right-arrow" /> instead of declaring a function.

  1. Right now, with image: () => <Img type="right-arrow" />, you will have to call the function to render the component.
<>
  {config.emailAddress.image()}
</>

I think the first approach is always easier.

This should also help you understand why SVGs can be loaded so easily.

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.

See this stackoverflow answer for implementation details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...