我有一个map()需要根据条件显示视图的功能.我查看了有关如何编写条件的React文档,这是您编写条件的方法:
{if (loggedIn) ? (
// Hello!
) : (
// ByeBye!
)}
Run Code Online (Sandbox Code Playgroud)
这是链接:https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator
所以,我试图在我的React应用程序中获取该知识并实现它.它结果是这样的:
render() {
return (
<div>
<div className="box">
{this.props.collection.ids
.filter(
id =>
// note: this is only passed when in top level of document
this.props.collection.documents[id][
this.props.schema.foreignKey
] === this.props.parentDocumentId
)
.map(id =>
{if (this.props.schema.collectionName.length < 0 ? (
<Expandable>
<ObjectDisplay
key={id}
parentDocumentId={id}
schema={schema[this.props.schema.collectionName]}
value={this.props.collection.documents[id]}
/>
</Expandable>
) : (
<h1>hejsan</h1>
)}
)}
</div>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用..!这是错误:
我感谢所有帮助!
May*_*kla 41
你正在使用ternary operator和if条件,使用任何一个.
由三元运营商:
.map(id => {
return this.props.schema.collectionName.length < 0 ?
<Expandable>
<ObjectDisplay
key={id}
parentDocumentId={id}
schema={schema[this.props.schema.collectionName]}
value={this.props.collection.documents[id]}
/>
</Expandable>
:
<h1>hejsan</h1>
}
Run Code Online (Sandbox Code Playgroud)
如果条件:
.map(id => {
if(this.props.schema.collectionName.length < 0)
return <Expandable>
<ObjectDisplay
key={id}
parentDocumentId={id}
schema={schema[this.props.schema.collectionName]}
value={this.props.collection.documents[id]}
/>
</Expandable>
return <h1>hejsan</h1>
}
Run Code Online (Sandbox Code Playgroud)
Ray*_*aga 33
如果你是像我一样的极简主义者。假设您只想渲染包含条目列表的记录。
<div>
{data.map((record) => (
record.list.length > 0
? (<YourRenderComponent record={record} key={record.id} />)
: null
))}
</div>
Run Code Online (Sandbox Code Playgroud)
删除if关键字。它应该只是predicate ? true_result : false_result。
也? :称为三元运算符。
三元条件中有两个语法错误:
if。在此处检查正确的语法。您在代码中缺少括号。如果您这样格式化:
{(this.props.schema.collectionName.length < 0 ?
(<Expandable></Expandable>)
: (<h1>hejsan</h1>)
)}
Run Code Online (Sandbox Code Playgroud)希望这有效!
这个我找到了简单的解决方案:
row = myArray.map((cell, i) => {
if (i == myArray.length - 1) {
return <div> Test Data 1</div>;
}
return <div> Test Data 2</div>;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64111 次 |
| 最近记录: |