React JSX: Access Props in Quotes

匿名 (未验证) 提交于 2019-12-03 01:58:03

问题:

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

For example:

The resulting HTML output is:

回答1:

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:



回答2:

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



回答3:

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

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



回答4:

Best practices are to add getter method for that :

getImageURI() {   return "images/" + this.props.image; }  

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



回答5:

For People, looking for answers w.r.t to 'map' function and dynamic data, here is a working example.

This gives the URL as "http://examole.com/randomview/images/2/dp_pics/182328.jpg" (random example)



回答6:

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 (       

Click to change image

); } }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!