简体   繁体   中英

How to add image in react

I can't find the right syntax for supplying an image from a URL.

<image src='url(' +${this.url}+ ')'
                 style={{
                   height: 'auto',
                   width: '100%'
                 }}></image>

Can you give me a source to know when to use: ${} , {} , ``, ""?

In your case you should write:

<image src= {this.url}
             style={{
               height: 'auto',
               width: '100%'
             }}></image>

You use {} when there is a var, "" when it's a string, and ${} when you are inside backquote ``

`` use mostly for if you don't want to break your code or string which mostly happen with '' or "" like this

console.log('string text line 1\n' +
'string text line 2');

solution use ``

console.log(`string text line 1

string text line 2`);

${} is used in `` and is equal to + in ''

var a = "hello";
 console.log(`string text line 1 ${a}
string text line 2`);

{} is JSON syntax and used for style object which accept only JSON if you are adding inline

"" is same to ''


Just use `` rather than ''

 <image src= `${this.url}`
             style={{
               height: 'auto',
               width: '100%'
             }}></image>

Since html attributes cannot be concatenated like myattr='my'+dynamic+'value React provides us the curly brace to use dynamic value:

<image src={'url(' + this.url + ')'} />

Notice, concatenation is done inside the curly brace {} .

But today, we use ES6+ features mostly, thus concatenating them using + operator is an ugly solution. Hence, we use template literal using tilde key `

<image src={`url${this.url}`} />

To use the variable inside the template literal, we use ${variable_name} .


Further, I suspect the url() function here, have you defined anywhere? Otherwise, you should not use, just use:

<image src={this.url} />

The value of src is just a path to the image src="path.jpg" but not src="url(path.jpg)" .

Also, is image a component? Otherwise, it should be <img /> tag not <image /> . If image is a component, then I suggest you to use Capitalized name in your component even if they are functional component.

<image src={this.url}
           style={{
                   height: 'auto',
                   width: '100%'
                 }}></image>

and if it's in the props you put {this.props.url}

All your javascript code should be inside {} operators when writing jsx.

${} is used when you are using template literal syntax ie ``.

<image url = {`url(${this.url})`} />

use template literals reference

<image src= {`${this.url}`}
             style={{
               height: 'auto',
               width: '100%'
             }}></image>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM