Soy nuevo en React y tengo problemas con la sintaxis. Tengo este bloque como un div dentro de mi función de renderizado. Cada cambio que hago va de un error de sintaxis a otro o simplemente no funciona.
<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>Recomiendo hacer una función:
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 no admite la conditional statement , pero admite el ternary operator , por lo que puede hacerlo así:
<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 gusta el siguiente enfoque cuando es solo una declaración if :
<div className="skillSection"> {this.state.challengeChoices.length < 0 && <ChallengeSkill key={i} {...para2} callback={this.madeSelection} /> } </div>Por supuesto, if/else tiene muchas opciones:
// 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> ) }