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

后端 未结 13 2326
南旧
南旧 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:24

    For maintainable code skip unnecessary abstractions like If and add some control logic with an early termination before the return statement in your render method, e.g.

    import React from 'react-native';
    
    let {
      Text
    } = React;
    
    let Main = React.createClass({
      setInitialState() {
        return { isShown: false }
      },
      render() {
        let content;
        if (this.state.isShown) {
          content = 'Showing true item'
        } else {
          return false;
        }
        return (
          {content}
        );
      }
    });
    

    Keeps you DRY. Lasting protection.

提交回复
热议问题