jsx中的if-else语句:ReactJS

时间:2017-05-18 11:05:54

标签: javascript reactjs react-native

我需要更改渲染函数并在给定特定状态时运行一些子渲染函数,

例如:

render() {
    return (   
        <View style={styles.container}>
            if (this.state == 'news'){
                return (
                    <Text>data</Text>
                )
            }
        </View>
    )
}

如何在不改变场景的情况下实现这一点,我将使用标签动态更改内容。

17 个答案:

答案 0 :(得分:59)

根据 DOC

  

if-else语句在JSX中不起作用。这是因为JSX才是   函数调用和对象构造的语法糖。

基本规则:

  

JSX基本上是syntactic sugar。编译之后,JSX表达式成为常规JavaScript函数调用并评估为JavaScript对象。我们可以将任何JavaScript expression嵌入到JSX中,方法是将它包装在大括号中。

但只有表达式不是语句,意味着我们不能在JSX内放置任何语句( if-else / switch / for )。

如果要有条件地渲染元素,请使用ternary operator,如下所示:

render() {
    return (   
        <View style={styles.container}>
            {this.state.value == 'news'? <Text>data</Text>: null }
        </View>
    )
}

另一个选择是,从jsx调用一个函数并将所有if-else逻辑放在其中,如下所示:

renderElement(){
   if(this.state.value == 'news')
      return <Text>data</Text>;
   return null;
}

render() {
    return (   
        <View style={styles.container}>
            { this.renderElement() }
        </View>
    )
}

答案 1 :(得分:8)

我喜欢它,而且工作正常。

constructor() {
   super();

   this.state ={
     status:true
   }
}

render() {
   return( 

     { this.state.status === true ?
           <TouchableHighlight onPress={()=>this.hideView()}>
             <View style={styles.optionView}>
               <Text>Ok Fine :)</Text>
             </View>
          </TouchableHighlight>
           :
           <Text>Ok Fine.</Text>
     }
  );
}

hideView(){
  this.setState({
    home:!this.state.status
  });
}

答案 2 :(得分:7)

我发现这种方式最好:

{this.state.yourVariable === 'news' && <Text>{data}<Text/>}

答案 3 :(得分:7)

您可以使用立即调用函数表达式(IIFE)来实现您所说的内容

render() {
    return (   
        <View style={styles.container}>
            {(() => {
              if (this.state == 'news'){
                  return (
                      <Text>data</Text>
                  )
              }
              
              return null;
            })()}
        </View>
    )
}

这是工作示例:

Edit awesome-yalow-eb2nu

但是,在您的情况下,您可以坚持使用三元运算符

答案 4 :(得分:2)

有一个Babel插件,可让您在JSX内编写条件语句,而无需使用JavaScript对其进行转义或编写包装器类。叫做JSX Control Statements

<View style={styles.container}>
  <If condition={ this.state == 'news' }>
    <Text>data</Text>
  </If>
</View>

需要根据Babel的配置进行一些设置,但是您无需导入任何内容,并且它具有条件渲染的所有优点,而无需离开JSX,从而使您的代码看起来很干净。

答案 5 :(得分:1)

你可以这样做。只是不要忘记在JSX组件之前放置“return”。

示例:

render() {
    if(this.state.page === 'news') {
        return <Text>This is news page</Text>;
    } else {
        return <Text>This is another page</Text>;
    }
}

从互联网上获取数据的示例:

import React, { Component } from 'react';
import {
    View,
    Text
} from 'react-native';

export default class Test extends Component {
    constructor(props) {
        super(props);

        this.state = {
            bodyText: ''
        }
    }

    fetchData() {
        fetch('https://example.com').then((resp) => {
            this.setState({
                bodyText: resp._bodyText
            });
        });
    }

    componentDidMount() {
        this.fetchData();
    }

    render() {
        return <View style={{ flex: 1 }}>
            <Text>{this.state.bodyText}</Text>
        </View>
    }
}

答案 6 :(得分:0)

JSX 中不需要 if else 条件。它提供了一个类似于三元运算符的函数来让事情发生,例如:

state={loading:false}
<View>
  {loading ? <Text>This is a test For if else condition</Text> : <ActivityIndicator/>
</View>

答案 7 :(得分:0)

刚试过:

return(
  <>
    {
      main-condition-1 && 
      main-condition-2 &&
      (sub-condition ? (<p>Hi</p>) : (<p>Hello</p>))
     }
  </>
)

让我知道你们的想法!!!

答案 8 :(得分:0)

                        <Card style={{ backgroundColor: '#ffffff', height: 150, width: 250, paddingTop: 10 }}>
                            
                            <Text style={styles.title}>     {item.lastName}, {item.firstName} ({item.title})</Text> 
                            <Text >     Email: {item.email}</Text>
                            {item.lastLoginTime != null ? <Text >     Last Login: {item.lastLoginTime}</Text> : <Text >     Last Login: None</Text>}
                            {item.lastLoginTime != null ? <Text >     Status: Active</Text> : <Text >     Status: Inactive</Text>}
                           
                        </Card>

答案 9 :(得分:0)

反应中具有if条件的嵌套循环的简单示例:

数据示例:

    menus: [
    {id:1, name:"parent1", pid: 0},
    {id:2, name:"parent2", pid: 0},
    {id:3, name:"parent3", pid: 0},
    {id:4, name:"parent4", pid: 0},
    {id:5, name:"parent5", pid: 0},
    {id:6, name:"child of parent 1", pid: 1},
    {id:7, name:"child of parent 2", pid: 2},
    {id:8, name:"child of parent 2", pid: 2},
    {id:9, name:"child of parent 1", pid: 1},
    {id:10, name:"Grand child of parent 2", pid: 7},
    {id:11, name:"Grand child of parent 2", pid: 7},
    {id:12, name:"Grand child of parent 2", pid: 8},
    {id:13, name:"Grand child of parent 2", pid: 8},
    {id:14, name:"Grand child of parent 2", pid: 8},
    {id:15, name:"Grand Child of Parent 1 ", pid: 9},
    {id:15, name:"Child of Parent 4 ", pid: 4},
    ]

嵌套循环和条件:

    render() {
    let subMenu='';
    let ssubmenu='';
    const newMenu = this.state.menus.map((menu)=>{
    if (menu.pid === 0){
    return (
    <ul key={menu.id}>
       <li>
          {menu.name}
          <ul>
             {subMenu = this.state.menus.map((smenu) => {
             if (menu.id === smenu.pid) 
             {
             return (
             <li>
                {smenu.name}
                <ul>
                   {ssubmenu = this.state.menus.map((ssmenu)=>{
                   if(smenu.id === ssmenu.pid)
                   {
                   return(
                   <li>
                      {ssmenu.name}
                   </li>
                   )
                   }
                   })
                   }
                </ul>
             </li>
             )
             }
             })}
          </ul>
       </li>
    </ul>
    )
    }
    })
    return (
    <div>
       {newMenu}
    </div>
    );
    }
    }

答案 10 :(得分:0)

if(condition1){ image1
}esleif(condition2){ image2
}else{ image3
}

对于上述多种情况,请检查以下代码,

render(){
return(
{
       (condition1)?
       <Image source={require('')}/>:
       (condition2)?
       <Image source={require('')}/>:
       <Image source={require('')}/>:

}
);}

答案 11 :(得分:0)

 render() {
     return (   
         <View style={styles.container}>
         (() => {                                                       
             if (this.state == 'news') {
                return  <Text>data</Text>
            }
            else 
             return  <Text></Text>
        })()
         </View>
     )
 }

https://react-cn.github.io/react/tips/if-else-in-JSX.html

答案 12 :(得分:0)

用开关盒代替if-else

  render() {
    switch (this.state.route) {
      case 'loginRoute':
        return (
            <Login changeRoute={this.changeRoute}
              changeName={this.changeName}
              changeRole={this.changeRole} />
        );
      case 'adminRoute':
        return (
            <DashboardAdmin
              role={this.state.role}
              name={this.state.name}
              changeRoute={this.changeRoute}
            />
        );
    }

答案 13 :(得分:0)

为此,我们可以使用三元运算符,或者如果只有一个条件,则使用“ &&”运算符。就像这样:- //如果不是这样的话

render(){

return (   
    <View style={styles.container}>
      {this.state == 'news') ?
           <Text>data</Text>
        : null}
    </View>
)

}

//这仅适用于一种情况或仅一种情况

render(){

return (   
    <View style={styles.container}>
      {this.state == 'news') &&
           <Text>data</Text>
        }
    </View>
)

}

答案 14 :(得分:0)

通常,我这样做:

_renderNews () {
  if (this.state.page === 'news') {
    return <Text>{data}</Text>
  }
  return null
}

render () {
  return (
    <View>{this._renderNews}</View>
  )
}

答案 15 :(得分:0)

你不能在返回块中提供if-else条件,使用三元块,this.state也是一个对象,你不应该将它与一个值进行比较,看看哪个状态要检查的值,也返回只返回一个元素,确保将它们包装在View

render() {
    return (
      <View style={styles.container}>
      {this.state.page === 'news'? <Text>data</Text>: null}
      </View>

     )
}

答案 16 :(得分:-1)

我们可以通过两种方式解决此问题:

  1. 通过仅添加空的<div>元素来编写else条件。
  2. 否则返回null。
render() {
    return (   
        <View style={styles.container}>
            if (this.state == 'news'){
                return (
                    <Text>data</Text>
                );
            }
            else {
                 <div> </div>
            }

        </View>
    )
}