jsx 中的 if-else 语句:ReactJS [英] if-else statement inside jsx: ReactJS

查看:38
本文介绍了jsx 中的 if-else 语句:ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to change render function and run some sub render function when a specific state given,

例如:

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.

推荐答案

Asper DOC:

As per DOC:

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

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

基本规则:

JSX 基本上是语法糖.编译后,JSX 表达式成为常规 JavaScript 函数调用并评估为 JavaScript 对象.我们可以通过以下方式在 JSX 中嵌入任何 JavaScript 表达式用大括号把它包起来.

JSX is fundamentally syntactic sugar. After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. We can embed any JavaScript expression in JSX by wrapping it in curly braces.

但是只有表达式而不是语句,这意味着我们不能直接在 JSX.

But only expressions not statements, means directly we can not put any statement (if-else/switch/for) inside JSX.

如果你想有条件地渲染元素,那么使用三元运算符,就像这样:

If you want to render the element conditionally then use ternary operator, like this:

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

另一种选择是,从 jsx 调用一个函数并将所有 if-else 逻辑放在里面,就像这样:

Another option is, call a function from jsx and put all the if-else logic inside that, like this:

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

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

这篇关于jsx 中的 if-else 语句:ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆