ReactJs - Creating an “If” component… a good idea?

后端 未结 13 2300
南旧
南旧 2020-12-12 17:11

I\'ve read in the React docs that \"if\" type statements can\'t be used in JSX code, because of the way JSX renders into javascript, it doesn\'t work out as one would expect

13条回答
  •  春和景丽
    2020-12-12 17:26

    render-if is a light weight function that will render an element if a condition is satisfied

    As an in-line expression

    class MyComponent extends Component {
      render() {
        return (
          {renderIf(1 + 2 === 3)(
            The universe is working
          )}
        );
      }
    }
    

    As a named function

    class MyComponent extends Component {
      render() {
        const ifTheUniverseIsWorking = renderIf(1 + 2 === 3);
        return (
          {ifTheUniverseIsWorking(
            The universe is still wroking
          )}
        )
      }
    }
    

    As a composed function

    const ifEven = number => renderIf(number % 2 === 0);
    const ifOdd = number => renderIf(number % 2 !== 0);
    
    class MyComponent extends Component {
      render() {
        return (
          {ifEven(this.props.count)(
            {this.props.count} is even
          )}
          {ifOdd(this.props.count)(
            {this.props.count} is odd
          )}
        );
      }
    }
    

提交回复
热议问题