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

前端 未结 6 1709
情话喂你
情话喂你 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:15

    Calculating the value, binding to a variable, then outputting later is better. If you do want complex logic inline, you could use && and ||:

    render() {
        return (
    { this.props.conditionA && Condition A || this.props.conditionB && Condition B || Neither }
    ) }

    Edit:

    As others pointed out, you can also remove that wrapping div and still use this approach:

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

提交回复
热议问题