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

查看:260
本文介绍了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.

推荐答案

根据 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基本上是 syntactic糖。编译之后,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.

但只有表达式而不是语句,意味着我们不能直接放任何语句( if-else JSX 内的/ switch / for

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天全站免登陆