反应数组中的条件渲染

时间:2020-02-26 10:53:33

标签: javascript reactjs ecmascript-6 jsx

我试图找出React中的条件渲染。我从API获得了五个类别,我只想根据类别条件打印一个p标签

我当前的尝试:

this.state.links.map(link => 
    div className="youtubeLinks">                       
        <p> print category 1</p>
        <p> print category 2</p>
        <p> print category 3</p>
        <p> print category 4</p>
        <p> print category 5</p>
    </div>

想要实现

if(link.category == 1){
<p> print category 1</p>
} 
if(link.category == 2){
<p> print category 2</p>
} 
if(link.category == 3){
<p> print category 3</p>
} 
if(link.category == 4){
<p> print category 4</p>
} 
if(link.category == 5){
<p> print category 5</p>
}

3 个答案:

答案 0 :(得分:1)

您可以这样做

C:\Scripts>powershell -command "& { c:\Scripts\sc.ps1; init }"
init : The term 'init' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:17
+ .\sc.ps1; init
+           ~~~~
+ CategoryInfo          : ObjectNotFound: (init:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
C:\Scripts>powershell -file c:\Scripts\sc.ps1 -command init
C:\Scripts>
C:\Scripts>powershell -file .\sc.ps1 -command init
C:\Scripts>

如果您只想在p标签内打印类别

this.state.links.map(link => 
    <div className="youtubeLinks">                       
        {link.category == 1 && <p> print category 1</p>}
        {link.category == 2 && <p> print category 2</p>}
        {link.category == 3 && <p> print category 3</p>}
        {link.category == 4 && <p> print category 4</p>}
        {link.category == 5 && <p> print category 5</p>}
        <img src={link.link} /> // Here is error img
    </div>
)

对于带有p标签的img

this.state.links.map(link => 
    <div className="youtubeLinks">                       
        <p> print category {link.category}</p>
    </div>
)

答案 1 :(得分:0)

你一切都很好,但需要一些修改

<div className="youtube-links">
 {this.state.links.map(link => (<p>Print category {link.category}</p>))}
</div>

答案 2 :(得分:0)

让我们说,您的数组仅由文本链接['link1', 'link2', 'link3]'组成,并且您希望将其映射并显示在该p中。地图的链接部分代表数组中的一项。我将其固定在下面。

//link represents one item. So when you then say return  

链接它将分别打印出阵列中的每个项目。

 <div className="youtubeLinks">                       
    {this.state.links.map(link => {
        return <p> print category {link}</p>
    })}
 </div>