我是 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>
当然,如果/否则有很多选择:
// 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>
)
}