在分支

时间:2017-01-11 01:55:41

标签: javascript reactjs

我是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>

3 个答案:

答案 0 :(得分:6)

推荐制作功能:

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>)
}

答案 1 :(得分:1)

jsx不支持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> ,因此您可以这样做:

me

答案 2 :(得分:1)

当它只是一个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>
    )
}