Access props inside quotes in React JSX

后端 未结 9 1202
广开言路
广开言路 2020-12-04 06:11

In JSX, how do you reference a value from props from inside a quoted attribute value?

For example:



        
相关标签:
9条回答
  • 2020-12-04 06:32

    React (or JSX) doesn't support variable interpolation inside an attribute value, but you can put any JS expression inside curly braces as the entire attribute value, so this works:

    <img className="image" src={"images/" + this.props.image} />
    
    0 讨论(0)
  • 2020-12-04 06:32

    Best practices are to add getter method for that :

    getImageURI() {
      return "images/" + this.props.image;
    }
    
    <img className="image" src={this.getImageURI()} />
    

    Then , if you have more logic later on, you can maintain the code smoothly.

    0 讨论(0)
  • 2020-12-04 06:40

    Instead of adding variables and strings, you can use the ES6 template strings! Here is an example:

    <img className="image" src={`images/${this.props.image}`} />
    

    As for all other JavaScript components inside JSX, use template strings inside of curly braces. To "inject" a variable use a dollar sign followed by curly braces containing the variable you would like to inject. For example:

    {`string ${variable} another string`}
    
    0 讨论(0)
  • 2020-12-04 06:43

    Note: In react you can put javascript expression inside curly bracket. We can use this property in this example.
    Note: give one look to below example:

    class LoginForm extends React.Component {
    
      constructor(props) {
        super(props);
    
        this.state = {i:1};
      }
    
      handleClick() {
        this.setState(prevState => ({i : prevState.i + 1}));
    
        console.log(this.state.j);  
      }
    
    
      render() {
    
        return (
          <div>
            <p onClick={this.handleClick.bind(this)}>Click to change image</p>
            <img src={'images/back'+ this.state.i+'.jpg'}/>
          </div>
          );
    
      }
    }
    
    0 讨论(0)
  • 2020-12-04 06:45

    If you're using JSX with Harmony, you could do this:

    <img className="image" src={`images/${this.props.image}`} />
    

    Here you are writing the value of src as an expression.

    0 讨论(0)
  • 2020-12-04 06:47

    If you want to use the es6 template literals, you need braces around the tick marks as well:

    <img className="image" src={`images/${this.props.image}`} />
    
    0 讨论(0)
提交回复
热议问题