Jsx 中的 if-else 语句: ReactJS

我需要改变呈现函数,并运行一些子呈现函数时,一个特定的状态给定,

例如:

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

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

296690 次浏览

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

例如:

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

根据 DOC:

If-else 语句在 JSX 中不起作用,这是因为 JSX 是公正的 syntactic sugar for function calls and object construction.

基本规则:

JSX 基本上是 语法糖。编译之后,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>
)
}

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

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


)
}

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

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

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

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

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

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

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

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

}

用开关格代替 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

我们可以用两种方法来解决这个问题:

  1. Write a else condition by adding just empty <div> element.
  2. 否则返回 null。
render() {
return (
<View style={styles.container}>
if (this.state == 'news'){
return (
<Text>data</Text>
);
}
else {
<div> </div>
}


</View>
)
}

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

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

return null;
})()}
</View>
)
}

下面是一个可行的例子:

Edit awesome-yalow-eb2nu

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

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

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

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

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

把密码写下来

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

如果你想在函数组件中使用一个 If判断语句,那么你可以从 jsx 调用一个函数,并把你所有的条件逻辑都放在里面。

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


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