[英]ReactJS syntax for if else with map function in branch
我是React的新手並且正在努力學習語法。 我在渲染函數中將此塊作為div。 我做的每一個更改都來自一個語法錯誤或另一個或只是不起作用。
<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>
推薦制作功能:
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不支持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>
當它只是一個if
語句時,我喜歡以下方法:
<div className="skillSection">
{this.state.challengeChoices.length < 0 &&
<ChallengeSkill key={i} {...para2} callback={this.madeSelection} />
}
</div>
當然,如果/ 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.