How can I write an else if structure using React (JSX) - the ternary is not expressive enough

前端 未结 6 1714
情话喂你
情话喂你 2021-01-01 18:47

I want to write the equivalent in react:

if (this.props.conditionA) {
    Condition A
} else if (this.props.conditionB) {
    

        
6条回答
  •  清歌不尽
    2021-01-01 19:13

    If you don't need the

    , just return the elements:

    render() {
      if (this.props.conditionA) {
        return Condition A;
      } else if (this.props.conditionB) {
        return Condition B;
      } else {
        return Neither;
      }
    }
    

    You can even move the last return statement out of the else block.


    In general, you don't have to embed everything inside JSX. It's perfectly fine to compute values beforehand, just like you do elsewhere:

    render() {
      let content;
      if (this.props.conditionA) {
        content = Condition A;
      } else if (this.props.conditionB) {
        content = Condition B;
      } else {
        content = Neither;
      }
    
      return 
    {content}
    ; }

    You have to do that whenever you need / want to use a statement.

提交回复
热议问题