如何在React Native中使用两个语句编写if条件

时间:2018-07-10 09:58:01

标签: javascript reactjs react-native

对于在 React Native

中如何匹配if else中的JavaScript之类的两个语句,我感到困惑

例如,

if(array.length != null && array.length >= 2){
    alert("Array Is Greater Than 2")
}else if(array.length != null ){
    alert("Array Is Less Than 2")
}else{
    alert("Array is null")
}

我知道如何在React Native中传递符号条件

例如,

{
    array.length != null &&
    <View>
        /* Content Here */
    </View>
}

{
    array.length != null ?
    <View>
        /* If Content Here */
    </View>
    :
    <View>
        /* Else Content Here */
    </View>
}

但是如果状态像第一个一样,该如何创建?

3 个答案:

答案 0 :(得分:3)

您可以嵌套三元条件,但是我不建议这样做,因为它不那么可读。另一个选择是,您可以将所有这些条件放入函数中,然后从render方法调用该函数。

赞:

renderElement () {
    if(array.length != null && array.length >= 2){
        alert("Array Is Greater Than 2");
        return <p>If condition</p>;
    }else if(array.length != null ){
        alert("Array Is Less Than 2");
        return <p>If-Else condition</p>;
    }else{
        alert("Array is null");
        return <p>Else condition</p>;
    }
}

render () {
    const element = this.renderElement();
    // now you can use element to render that element at any place
}

嵌套三元条件:

{
    array.length != null && array.length >= 2 ?
        <View>
            /* Array Is Greater Than 2 */
        </View>
    :
        array.length != null?
            <View>
                /* Array Is Less Than 2 */
            </View>
        :
            <View>
                /* Array Is Null */
            </View>
}

答案 1 :(得分:2)

您可以像这样嵌套三元条件检查

{
    array.length != null && array.length >= 2 ?
    <View>
        /* If Content Here */
    </View>
    :
    array.length != null?
     <View>
        /* Else if Content Here */
    </View>: 
    <View>
        /* Else Content Here */
    </View>
}

但是,您可以在@MayankShukla建议的渲染中调用的函数中使用if-else简单地执行此操作,因为它比嵌套的三元运算符更易读

答案 2 :(得分:1)

实际上,我没有找到一种更清洁的方式来实现您想要的方式。

理论上,您可以使用嵌套三元运算符来完成此操作,但是它很脏而且不可读。

我始终坚持创建单独的方法,并在渲染器中调用它:

renderView() {
  if(array.length != null && array.length >= 2) {
    return <div>Array Is Greater Than 2</div>
  } else if(array.length != null ) {
    return <div>Array Is Less Than 2</div>
  } else {
    return </div>
  }
}

render() {
  return <div>{this.renderView()}</div>
}