Javascript jsx中的条件输出HTML
我正在尝试更改一些jsx,这些jsx目前只是循环并输出jsx,当我尝试根据数组对象中的值将循环更改为输出时,我在代码中得到一个错误,因为它与我尝试输出html的方式类似 数组中有一个名为Group的值,如果组名与上一个组名不同,则输出一个标签以显示新组名 我首先要说的是Javascript jsx中的条件输出HTML,javascript,reactjs,jsx,Javascript,Reactjs,Jsx,我正在尝试更改一些jsx,这些jsx目前只是循环并输出jsx,当我尝试根据数组对象中的值将循环更改为输出时,我在代码中得到一个错误,因为它与我尝试输出html的方式类似 数组中有一个名为Group的值,如果组名与上一个组名不同,则输出一个标签以显示新组名 我首先要说的是 <Container className="float-left"> { this.Store.SearchResults.map( template =>
<Container className="float-left">
{
this.Store.SearchResults.map( template =>
<TemplateCard
key={template.Name}
....
>
{ template.Name }
</TemplateCard>)
}
</Container>
{
this.Store.SearchResults.map(模板=>
{template.Name}
)
}
我想做的是
<Container className="float-left">
{
this.Store.SearchResults.map( template =>
{
var lastGroup;
if(template.Group !== lastGroup ){
// output group name
<div>
<Label>{template.Group}</Label>
</div>
}
}
<TemplateCard
key={template.Name}
....
>
{ template.Name }
</TemplateCard>)
}
</Container>
{
this.Store.SearchResults.map(模板=>
{
var-lastGroup;
如果(template.Group!==lastGroup){
//输出组名
{template.Group}
}
}
{template.Name}
)
}
这就产生了错误意外标记,应为“,”您可以使用三元运算符,如果条件为true,则该运算符将呈现div,否则将呈现null:
{template.Group !== lastGroup ?
<div>
<Label>{template.Group}</Label>
</div>
: null}
{template.Group!==lastGroup?
{template.Group}
:null}
您的代码存在许多问题。
不确定是否需要在用例中使用map两次,但由于.map()
应返回单个元素,因此应将整个内容包装在一个
this.Store.SearchResults.map( (template, index) =>
{
var lastGroup; // Make sure to initialize it with some value
return (
<React.Fragment key={index}>
{template.Group !== lastGroup &&
(<div>
<Label>{template.Group}</Label>
</div>)
}
<TemplateCard
key={template.Name}
....
>
{ template.Name }
</TemplateCard>
</React.Fragment>);
}
this.Store.SearchResults.map((模板,索引)=>
{
var lastGroup;//确保使用一些值初始化它
返回(
{template.Group!==lastGroup&&
(
{template.Group}
)
}
{template.Name}
);
}
需要记住的更多改进/事项-
.map()
中添加返回语句.map()
内的元素中添加一个键好的,谢谢你的帮助 我无法让它工作,正如Jayakumar所说,我可能需要发布更多的代码。无论如何,我现在已经设法以不同的方式解决了问题。通过使用单独的数组并在下面添加一个新的部分来解决问题,这可能会在以后成为一个问题,但现在就可以了
谢谢您是否需要
.map()
两次?不确定?有点新的反应,所以不确定要做什么..检查此项,请发布完整的容器代码谢谢,这会给出相同的错误…意外标记,预期“,”在map
内部使用var..
非常好,只需使用一个大括号语法。谢谢你的评论和代码。我将尝试一下。有一个返回值,但它更高,为了保持简单而被删除。关键是模板名。关键是将它包装在一个React片段中,以便它返回一个顶级元素来自地图的ent
。你可以给它任何你想要的键