[英]ReactJS syntax for if else with map function in branch
I'm new to React and struggling with the syntax. 我是React的新手并且正在努力学习语法。 I have this block as a div inside my render function. 我在渲染函数中将此块作为div。 Every change I make goes from one syntax error or another or just doesn't work. 我做的每一个更改都来自一个语法错误或另一个或只是不起作用。
<div className="skillSection">
{
if (this.state.challengeChoices.length < 0) {
this.state.challengeChoices.map((para2, i) =>
<ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
}
else {
return <div>Hello world</div>
}
}
</div>
Recommend making a function: 推荐制作功能:
renderSkillSection: function(){
if (this.state.challengeChoices.length < 0) {
return this.state.challengeChoices.map((para2, i) =>
<ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
}
else {
return <div>Hello world</div>
}
},
render: function(){
return (<div className="skillSection">
{this.renderSkillSection()}
</div>)
}
jsx doesn't support conditional statement
, but it support ternary operator
, so you can do it like this: jsx不支持conditional statement
,但它支持ternary operator
,所以你可以这样做:
<div className="skillSection">
{ this.state.challengeChoices.length < 0 ? (
this.state.challengeChoices.map((para2, i) =>
<ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)) : ( <div>Hello world</div>)
}
</div>
I like the following approach when it's just an if
statement: 当它只是一个if
语句时,我喜欢以下方法:
<div className="skillSection">
{this.state.challengeChoices.length < 0 &&
<ChallengeSkill key={i} {...para2} callback={this.madeSelection} />
}
</div>
Of course, if/else has many options: 当然,如果/ else有很多选择:
// Use inline if/else with some more readable spacing/indentation
render() {
return (
<div className="skillSection">
{this.state.challengeChoices.length < 0 ? (
<ChallengeSkill key={i} {...para2} callback={this.madeSelection} />
) : (
<div>False</div>
)}
</div>
)
}
// Define as variable
render() {
let dom = <div>False</div>;
if (this.state.challengeChoices.length < 0) {
dom = <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />;
}
return (
<div className="skillSection">
{dom}
</div>
)
}
// Use another method
getDom() {
if (this.state.challengeChoices.length < 0) {
return <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />;
}
return <div>False</div>;
}
render() {
return (
<div className="skillSection">
{this.getDom()}
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.