Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jsx:ReactJS中的if-else语句_Javascript_Reactjs_React Native - Fatal编程技术网

Javascript jsx:ReactJS中的if-else语句

Javascript jsx:ReactJS中的if-else语句,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我需要更改渲染函数并在给定特定状态时运行一些子渲染函数 例如: render() { return ( <View style={styles.container}> if (this.state == 'news'){ return ( <Text>data</Text> ) }

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

例如:

render() {
    return (   
        <View style={styles.container}>
            if (this.state == 'news'){
                return (
                    <Text>data</Text>
                )
            }
        </View>
    )
}
render(){
报税表(
如果(this.state=='news'){
返回(
数据
)
}
)
}

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

您可以这样做。只是别忘了在JSX组件前面加上“return”

例如:

render() {
    if(this.state.page === 'news') {
        return <Text>This is news page</Text>;
    } else {
        return <Text>This is another page</Text>;
    }
}
render(){
如果(this.state.page==='news'){
返回这是新闻页面;
}否则{
返回这是另一页;
}
}
从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>
    }
}
import React,{Component}来自'React';
进口{
看法
正文
}从“反应本机”;
导出默认类测试扩展组件{
建造师(道具){
超级(道具);
此.state={
正文:“”
}
}
fetchData(){
取('https://example.com)。然后((resp)=>{
这是我的国家({
bodyText:resp.\u bodyText
});
});
}
componentDidMount(){
这是fetchData();
}
render(){
返回
{this.state.bodyText}
}
}
根据

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

基本规则:

JSX从根本上说是一种安全的解决方案。编译后,JSX表达式成为常规JavaScript函数调用,并对JavaScript对象求值。我们可以在JSX中嵌入任何内容,方法是将其用大括号括起来

但只有表达式而不是语句,这直接意味着我们不能将任何语句(if-else/switch/for)放入其中


如果要有条件地渲染元素,请使用
三元运算符
,如下所示:

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

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

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

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

     )
}
render(){
返回(
{this.state.page=='news'?数据:null}
)
}

我发现这样最好:

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

我确实喜欢这个,而且它工作得很好

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
  });
}
constructor(){
超级();
这个州={
状态:正确
}
}
render(){
报税表(
{this.state.status===true?
this.hideView()}>
好:)
:
好的。
}
);
}
hideView(){
这是我的国家({
主页:!this.state.status
});
}

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


数据

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

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

//This is for if else

render() {

return (   
    <View style={styles.container}>
      {this.state == 'news') ?
           <Text>data</Text>
        : null}
    </View>
)
//这是用于if-else的
render(){
报税表(
{this.state=='news')?
数据
:null}
)
}

//这仅适用于if或仅适用于一个条件
render(){
报税表(
{this.state=='news')&&
数据
}
)

}用开关盒代替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(){
交换机(this.state.route){
案例“登录路线”:
返回(
);
案例“adminRoute”:
返回(
);
违约:
返回;
}
render(){
报税表(
(() => {                                                       
如果(this.state=='news'){
返回数据
}
其他的
返回
})()
)
}

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

  • 通过只添加空的
    元素来编写else条件
  • 否则返回null
  • render(){
    报税表(
    如果(this.state=='news'){
    返回(
    数据
    );
    }
    否则{
    }
    )
    }
    
    您可以通过使用立即调用的函数表达式(IIFE)来实现您所说的

    render(){
    报税表(
    {(() => {
    如果(this.state=='news'){
    返回(
    数据
    )
    }
    返回null;
    })()}
    )
    }
    
    以下是工作示例:


    但是,在您的情况下,可以使用三元运算符在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>
        );
        }
        }
    
    render(){
    让子菜单=“”;
    设ssubmenu='';
    const newMenu=this.state.menus.map((菜单)=>{
    如果(menu.pid==0){
    返回(
    
    • {menu.name}
        {子菜单=this.state.menus.map((smenu)=>{ 如果(menu.id==smenu.pid) { 返回(
      • {smenu.name}
          {ssubmenu=this.state.menus.map((ssmenu)=>{ if(smenu.id==ssmenu.pid) { 返回(
        • {ssmenu.name}
        • ) }
           render() {
               return (   
                   <View style={styles.container}>
                   (() => {                                                       
                       if (this.state == 'news') {
                          return  <Text>data</Text>
                      }
                      else 
                       return  <Text></Text>
                  })()
                   </View>
               )
           }
          
          render() {
              return (   
                  <View style={styles.container}>
                      {(() => {
                        if (this.state == 'news'){
                            return (
                                <Text>data</Text>
                            )
                        }
                        
                        return null;
                      })()}
                  </View>
              )
          }
          
              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>
              );
              }
              }
          
                                  <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>
          
          return(
            <>
              {
                main-condition-1 && 
                main-condition-2 &&
                (sub-condition ? (<p>Hi</p>) : (<p>Hello</p>))
               }
            </>
          )