【问题标题】:React Native Variable assignment when doing conditional rendering?在进行条件渲染时反应原生变量赋值?
【发布时间】:2018-06-02 01:31:51
【问题描述】:

我有一个构建视图的组件,但只有部分项目应根据数据呈现。但是,对于呈现的每个项目,我都会跟踪其计数。有没有办法在 render() 中做到这一点?

例如,类似:

render() {
    let count = 0;
    return (
        <View>

            { if condition1:
                 this.renderOptions(name='one', current_count=count);
                 count += 1;
            }
            { if condition2:
                 this.renderOptions(name='two', current_count=count);
                 count += 1;
            }
            { if condition3:
                 this.renderOptions(name='three', current_count=count);
            }

        </View>
    );
}

基本上,count 应该跟踪在特定条件下实际渲染了多少元素。每次条件为真并且renderOptions() 根据count 呈现特定项目时,它都会递增。

我知道有 &amp;&amp; 运算符,但是这样的事情会引发错误:

{ condition1 && this.renderOptions(name='one', current_count=count) }
{ condition1 && count++ }

但是这个错误:

未定义不是对象

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    而不是

    { condition1 && count++ }
    

    你可以写

    { condition1 && incrementCounter }
    

    然后在incrementCounter 函数中做count++(这将返回null)

    【讨论】:

    • 但是count是在render()中声明的局部变量?
    • 将其保持在状态!
    猜你喜欢
    • 2017-06-24
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2022-01-17
    相关资源
    最近更新 更多