分支中带有映射函数的 if else 的 ReactJS 语法

IT技术 javascript reactjs
2021-05-16 09:54:44

我是 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个回答

推荐做一个函数:

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>

当然,if/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>
    )
}