版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SpicyBoiledFish/article/details/79817247
目前我们使用的React Native或者ReactJS中,经常会使用到三目运算符来展现不同条件状态下的界面效果;此时我们就用到了三目运算啊。举例说明:
{this.state.isMyIntro ? <MyIntro /> : null}
这就是一个很简单的三目运算,来表达不同页面展示;当this.state.isMyIntro为true的情况下,就展示MyIntro组件;否则就不展示。
那么如果我们碰到条件有三种情况的?或者四种情况下的呢?首先这肯定是可以使用基本的if条件语句的;那么我们看看三目运算怎么去写这种嵌套下的条件:
<TouchableOpacity onPress={()=>this.onPressButton(index)} style={[styles.button, index == 2 ? {right:100, bottom:200} : (index == 1 ? {left:deviceWidth * 0.5,marginLeft: -60, bottom:200} : {left:deviceWidth * 0.5,marginLeft: -60, bottom:270})]}>
</TouchableOpacity>
三目运算可以用在任意你想用的地方,比方style中,我们抽出来简化下看:
index == 2 ? {right:100} : (index == 1 ? {right:120} : {right:140})
1. 当index==2的时候,让right为100;
2. 当index!=2的时候,判断index是否为1;如果index==1的时候,让right为120;
3. 当index!=2的时候;且index也!=1的时候,让right为140;