ReactJS return 条件判断的几种形式

来源:互联网 发布:高达模型淘宝店 编辑:程序博客网 时间:2024/05/17 08:10

原文地址:http://blog.csdn.net/yf275908654/article/details/51078215

在React中,一个组件的HTML标签与生成这些标签的代码内在地紧密联系在一起。这意味着你可以轻松的利用JavaScript强大的魔力,比如循环和条件判断等。

想要在组件中添加条件判断,似乎是件比较困难的事情,因为if/else逻辑很难用HTML标签来表达。直接在JSX中加入if语句会渲染出无效的javascript:

var IvanIf = React.createClass({    render: function () {        return(        <!--会渲染出无效的js的-->            <div className={if(true){ 'is-complete' }}> ... </div>        );    }});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

解决的办法有以下几种:

  • 使用三目运算符
  • 设置一个变量,并在属性中引用它
  • 讲逻辑信息封装到函数中
  • 使用 && 运算符

  • 三目运算符
var IvanIf = React.createClass({    getInitialState:function () {        return { isComplete:true };    },    render: function () {        return(            <div className={ this.state.isComplete ? 'is-complete' : '' }> Hello Ivan .</div>        );    }});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

虽然以上的三目运算符可以正常运行,但如果你想要在其他情况下很好的应用react Component时,可能就显得笨重又麻烦了,所以此方法是不做推荐使用的。


  • 使用变量
var IvanIf = React.createClass({    getInitialState:function () {        return { isComplete:true };    },    getIsComplete:function(){      return this.state.isComplete ? 'is-complete' : '' ;    },    render: function () {        var isComplete = this.getIsComplete();        return(            <div className={ isComplete }> Hello Ivan .</div>        );    }});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

其实就是将条件判断单独的抽离出去,在render中使用函数调用的形式来获取条件结果。


  • 使用函数
var IvanIf = React.createClass({    getInitialState:function () {        return { isComplete:false };    },    getIsComplete:function(){      return this.state.isComplete ? 'is-complete' : '' ;    },    render: function () {        return(            <div className={ this.getIsComplete() }> Hello Ivan .</div>        );    }});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

有种然并卵的赶脚


  • 使用逻辑与(&&)运算符
var IvanIf = React.createClass({    getInitialState:function () {        return { isComplete:false };    },    render: function () {        return(            <div className={ this.state.isComplete && 'is-complete' }> Hello Ivan .</div>        );    }});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

由于对于null 或 false 值,React不会输出任何内容,因此可以使用一个后面跟随了期望字符串的boolean值来实现条件判断。 
如果这个boolean值为true,那么后续的字符串会被使用,反之,则不会被使用

原创粉丝点击