【问题标题】:if-else statement inside jsx: ReactJSjsx 中的 if-else 语句:ReactJS
【发布时间】:2017-10-18 03:59:57
【问题描述】:

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

例如:

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

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

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    根据DOC

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

    基本规则:

    JSX 基本上是syntactic sugar。编译后,JSX 表达式成为常规的 JavaScript 函数调用并计算为 JavaScript 对象。我们可以在 JSX 中嵌入任何 JavaScript expression,方法是将其包裹在花括号中。

    但只有表达式而不是语句,直接意味着我们不能在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>
        )
    }
    

    【讨论】:

    • 我可以那样做吗? render() { return ( if (this.state == 'news'){ return ( data ) }
    • 所以返回内部返回是可能的吗?或同一渲染功能场景中的两个不同返回我需要更改返回的子内容
    • 是的,这是可能的,但是,以不同的方式,我们不能直接在 JSX 中使用 if/else,所以使用三元运算符作为条件,使用这个:render() { return ( &lt;View style={styles.container}&gt; {this.state == 'news' ? &lt;Text&gt;data&lt;/Text&gt; : null } &lt;/View&gt; ) }
    • ` { if (this.state.page == 'sohbet'){ } ` 不可能? }
    • 在文档中有很好的解释,请检查原因:reactjs.cn/react/tips/if-else-in-JSX.html
    【解决方案2】:

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

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

    下面是工作示例:

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

    【讨论】:

    • @Yusufbek 你能帮我解释一下为什么在这部分“ if (this.state == 'news'){ return (
      data1data2文本> ) }" 不起作用
    • 意思是在上面的返回中我们使用 div 表示多个元素 2 文本
    • @AakashMathur 它应该可以工作。确保你只返回 1 个根元素,并且你有 else 语句返回 null
    • 您可以通过切换到 Vue 来实现更直观的解决方案。令人难以置信的是,必须为如此基本的事情进行这样的黑客攻击。
    【解决方案3】:

    我觉得这样最好:

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

    【讨论】:

    • 我同意,这是最好的。不需要使用三元运算符返回 null ;)
    • 这应该添加到主要答案中。
    • 在我的情况下如何使用它?如果我像这样使用它{localStorage.getItem('token') &amp;&amp; &lt;Typography&gt;Invalid Login&lt;/Typography&gt;}它甚至会在提交表单之前呈现。 *.com/questions/60577971/…
    • 这对我有帮助,但是,我必须将元素包装在 ...> 中。
    【解决方案4】:

    我确实喜欢这个并且它工作正常。

    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
      });
    }
    

    【讨论】:

    • @Pierre.Vriens 可以在 render() 方法中使用三元运算符而不是 if-else。语法:- 条件? expr1 : expr2 前。 if (this.state.status === true) { } else { }
    【解决方案5】:

    你可以这样做。只是不要忘记在你的 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>
        }
    }
    

    【讨论】:

    • 你能给我看一个完整的工作示例吗?对不起,我是新手
    • @user8026867 添加示例
    • 我想从函数内部返回
    • @user8026867 你可以创建一个函数并在那里返回 JSX 组件。试试看你能不能做到,否则我给你举个例子。
    • alert 工作正常,但在 .then 之后没有渲染发生=> { alert(res.text()); return {res.text()} }) .catch((errorMessage, statusCode) => { alert(errorMessage); }) }跨度>
    【解决方案6】:

    有一个 Babel 插件允许您在 JSX 中编写条件语句,而无需使用 JavaScript 转义它们或编写包装类。它叫JSX Control Statements

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

    根据您的 Babel 配置需要进行一些设置,但您不必导入任何内容,它具有条件渲染的所有优点,而无需离开 JSX,这让您的代码看起来非常干净。

    【讨论】:

      【解决方案7】:

      用 switch case 代替 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}
                  />
              );
            default: 
              return <></>;
          }
      

      【讨论】:

      • 你缺少一个默认返回值,它应该不是undefined
      【解决方案8】:
       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

      【讨论】:

        【解决方案9】:

        React中带有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】:
                                  <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>
          

          【讨论】:

            【解决方案11】:

            JSX 中不需要if else 条件。它提供了一个类似于三元运算符的功能来为您完成这件事,例如:

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

            【讨论】:

              【解决方案12】:

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

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

              【讨论】:

              • 我的错,没有看到react-native标签,应该是View而不是div
              • 顺便说一句,我需要在 RNFetchBlob 函数之后返回文本
              • pulldata() { RNFetchBlob.fetch('GET', 'bigdsas', { }) .then((res) => { alert(res.text()); return aaaf }) .catch((errorMessage, statusCode) => { alert(errorMessage); }) return iop }
              【解决方案13】:

              刚刚试过:

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

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

              【讨论】:

                【解决方案14】:

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

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

                }

                //This is only for if or only for one condition
                
                render() {
                
                return (   
                    <View style={styles.container}>
                      {this.state == 'news') &&
                           <Text>data</Text>
                        }
                    </View>
                )
                

                }

                【讨论】:

                  【解决方案15】:

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

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

                  【讨论】:

                    猜你喜欢
                    相关资源
                    最近更新 更多
                    热门标签