繁体   English   中英

ReactJS语法,用于if分支中的map函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM