简体   繁体   中英

Render elements from a template

I have a lot of elements but no idea of how to render them but to write 40 lines of jsx

<p>{this.props.data.list[0].dt_txt}</p>
<p>{this.props.data.list[1].dt_txt}</p>
<p>{this.props.data.list[2].dt_txt}</p>
<p>{this.props.data.list[3].dt_txt}</p>
<p>{this.props.data.list[4].dt_txt}</p>
<p>{this.props.data.list[5].dt_txt}</p>
<p>{this.props.data.list[6].dt_txt}</p>
<p>{this.props.data.list[7].dt_txt}</p>
<p>{this.props.data.list[8].dt_txt}</p>
<p>{this.props.data.list[9].dt_txt}</p>
<p>{this.props.data.list[10].dt_txt}</p>
<p>{this.props.data.list[11].dt_txt}</p>
<p>{this.props.data.list[12].dt_txt}</p>
<p>{this.props.data.list[13].dt_txt}</p>
<p>{this.props.data.list[14].dt_txt}</p>

and so on...

so how could i create a template to render them all with less mess?

You can embed arbitrary JavaScript expressions in your JSX, so for your example, it should look like this

... // Other markups
{ 
    this.props.data.list.map(item => {
        return <p key={item.dt_txt}>{item.dt_txt}</p>
    });
}
... // Other markups

Note that you must wrap your expression in {} within your JSX, or else, it will be rendered like plain text.

To learn more about why you need to specify a key like above, you can refer to this link

You need to loop over the items in the list. The react docs explain this pretty well https://reactjs.org/docs/lists-and-keys.html

this.props.data.list.map((listItem) =>
  <p key={listItem.id}>{listItem.dt_text}</p>
);

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