Javascript jsx 中的 if-else 语句:ReactJS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44046037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if-else statement inside jsx: ReactJS
提问by user8026867
I need to change render function and run some sub render function when a specific state given,
我需要更改渲染函数并在给定特定状态时运行一些子渲染函数,
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.
如何在不改变场景的情况下实现这一点,我将使用选项卡动态更改内容。
回答by Mayank Shukla
As per DOC:
根据DOC:
if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.
if-else 语句在 JSX 中不起作用。这是因为 JSX 只是函数调用和对象构造的语法糖。
Basic Rule:
基本规则:
JSX is fundamentally syntactic sugar. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. We can embed any JavaScript expressionin JSX by wrapping it in curly braces.
JSX 基本上是语法糖。编译后,JSX 表达式成为常规 JavaScript 函数调用并评估为 JavaScript 对象。我们可以通过用花括号将任何JavaScript 表达式嵌入到 JSX 中。
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 jsxand put all the if-elselogic 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>
)
}
回答by sooper
I find this way is the nicest:
我发现这种方式是最好的:
{this.state.yourVariable === 'news' && <Text>{data}<Text/>}
回答by Manish
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
});
}
回答by Chase Sandmann
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. It's called JSX Control Statements:
有一个 Babel 插件,它允许您在 JSX 中编写条件语句,而无需使用 JavaScript 对其进行转义或编写包装类。它被称为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,这使您的代码看起来非常干净。
回答by Jagjot
You can do this. Just don't forget to put "return" before your JSX component.
你可以这样做。只是不要忘记在您的 JSX 组件之前放置“返回”。
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>
}
}
回答by Yusufbek
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>
)
}
})()}
</View>
)
}
Here is the working example:
这是工作示例:
But, In your case, you can stick with the ternary operator
但是,就您而言,您可以坚持使用三元运算符
回答by Viraj Singh
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}
/>
);
}
回答by user193679
render() {
return (
<View style={styles.container}>
(() => {
if (this.state == 'news') {
return <Text>data</Text>
}
else
return <Text></Text>
})()
</View>
)
}
回答by Aniket_1997
In two ways we can solve this problem:
我们可以通过两种方式解决这个问题:
- Write a else condition by adding just empty
<div>element. - or else return null.
- 通过仅添加空
<div>元素来编写 else 条件。 - 否则返回空值。
render() {
return (
<View style={styles.container}>
if (this.state == 'news'){
return (
<Text>data</Text>
);
}
else {
<div> </div>
}
</View>
)
}
回答by Shubham Khatri
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 只返回一个元素,确保将它们包装在一个视图中
render() {
return (
<View style={styles.container}>
{this.state.page === 'news'? <Text>data</Text>: null}
</View>
)
}


