简体   繁体   English

jsx 中的 if-else 语句:ReactJS

[英]if-else statement inside jsx: ReactJS

I need to change render function and run some sub render function when a specific state given,当给出特定的 state 时,我需要更改渲染 function 并运行一些子渲染 function,

For example:例如:

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

How can I implement that without changing scenes, I will use tabs to change content dynamically.如何在不改变场景的情况下实现这一点,我将使用选项卡动态更改内容。

As per DOC :根据文档

if-else statements don't work inside JSX. if-else 语句在 JSX 中不起作用。 This is because JSX is just syntactic sugar for function calls and object construction.这是因为 JSX 只是函数调用和对象构造的语法糖。

Basic Rule:基本规则:

JSX is fundamentally syntactic sugar . JSX 从根本上说是语法糖 After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects.编译后,JSX 表达式成为常规的 JavaScript 函数调用并计算为 JavaScript 对象。 We can embed any JavaScript expression in JSX by wrapping it in curly braces.我们可以在 JSX 中嵌入任何JavaScript 表达式,方法是将其包裹在花括号中。

But only expressions not statements, means directly we can not put any statement ( if-else/switch/for ) inside JSX .但是只有表达式而不是语句,直接意味着我们不能在JSX中放置任何语句( if-else/switch/for )。


If you want to render the element conditionally then use ternary operator , like this:如果要有条件地渲染元素,请使用ternary operator ,如下所示:

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

Another option is, call a function from jsx and put all the if-else logic inside that, like this:另一种选择是,从jsx调用一个函数并将所有if-else逻辑放入其中,如下所示:

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

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

You can achieve what you are saying by using Immediately Invoked Function Expression (IIFE)您可以通过使用立即调用函数表达式 (IIFE) 来实现您所说的

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

Here is the working example:这是工作示例:

编辑 awesome-yalow-eb2nu

But, In your case, you can stick with the ternary operator但是,在您的情况下,您可以坚持使用三元运算符

我发现这种方式是最好的:

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

I do like this and its working fine.我确实喜欢这个并且它工作正常。

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

You can do this.你可以这样做。 Just don't forget to put "return" before your JSX component.只是不要忘记在你的 JSX 组件之前加上“return”。

Example:例子:

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

Example to fetch data from internet:从互联网获取数据的示例:

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

There's a Babel plugin that allows you to write conditional statements inside JSX without needing to escape them with JavaScript or write a wrapper class.有一个 Babel 插件允许您在 JSX 中编写条件语句,而无需使用 JavaScript 转义它们或编写包装类。 It's called JSX Control Statements :它被称为JSX 控制语句

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

It takes a bit of setting up depending on your Babel configuration, but you don't have to import anything and it has all the advantages of conditional rendering without leaving JSX which leaves your code looking very clean.根据您的 Babel 配置需要进行一些设置,但您不必导入任何内容,它具有条件渲染的所有优点,而无需离开 JSX,这使您的代码看起来非常干净。

What about switch case instead of if-else用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 <></>;
    }
 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 https://react-cn.github.io/react/tips/if-else-in-JSX.html

Simple example of nested loop with if condition in React : React中带有 if 条件的嵌套循环的简单示例:

Data example:数据示例:

    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},
    ]

Nested Loop and Condition:嵌套循环和条件:

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

There is no need for the if else condition in JSX. JSX 中不需要if else条件。 It provides a function like ternary operator to make the thing happen for you, example:它提供了一个像三元运算符这样的函数来让事情发生在你身上,例如:

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

You can't provide if-else condition in the return block, make use of ternary block, also this.state will be an object, you shouldn't be comparing it with a value, see which state value you want to check, also return returns only one element, make sure to wrap them in a View您不能在返回块中提供 if-else 条件,使用三元块,而且 this.state 将是一个对象,您不应该将它与值进行比较,看看您要检查哪个状态值,也return 只返回一个元素,确保将它们包装在 View 中

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

     )
}

Usually, I do this: 通常,我这样做:

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

render () {
  return (
    <View>{this._renderNews}</View>
  )
}
if(condition1){ image1
}esleif(condition2){ image2
}else{ image3
}

For multiple condition like above, check the code mentioned below, 对于上述多种情况,请检查以下代码,

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

}
);}

In two ways we can solve this problem:我们可以通过两种方式解决这个问题:

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

        </View>
    )
}

Just Tried that:刚刚试过:

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

Let me know what you guys think!!!让我知道你们的想法!!!

Just Write Down The Code只需写下代码

 <> 
    {row.photo != null ? <img src={serverPath(row.photo)} className='img-fluid shadow-4' alt="" /> : ''}
 </>

If you want to use an conditional statement in functional component then you can call a function from jsx and put all your conditional logic inside it.如果要在功能组件中使用条件语句,则可以从 jsx 调用 function 并将所有条件逻辑放入其中。

conditionalRender(){
   if(state === 'news') {
      return <Text>data</Text>;
   }
   else(state !== 'news') {
      return <Text>Static Value</Text>;
   }
}

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

For this we can use ternary operator or if there is only one condition then "&&" operator .Like this:-为此,我们可以使用三元运算符,或者如果只有一个条件,则使用“&&”运算符。像这样:-

//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>
)

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM