如何在React Native组件中有条件地渲染样式?

时间:2020-01-31 19:32:40

标签: react-native

我有一个自定义组件,可在数据可用时提供呈现的数据列表。

但是,在下面的示例中data = []的情况下,当数据不可用时,我想对其应用其他样式。

return (
                        <FollowableArticleListTemplate
                            style={hasData}
                            title={ title }
                            data={ [] }
                            isFollowing={ isFollowing }
                            onToggleFollow={ id ? () => toggleSourceFollow(id, isFollowing, title) : null }
                            setListRef={ this.setListRef }
                            contentType="source"
                        />
                    );

我正在寻找的东西是这样的: style = {hasData}

data.length > 0 为此组件使用以下样式:style={hasData} 否则,请使用以下样式组件:style={noData}

1 个答案:

答案 0 :(得分:1)

这可以通过使用三元运算符轻松实现。首先,您必须使用状态来有条件地使用数据,而不是直接将其值提供给组件。

return (
                        <FollowableArticleListTemplate
                            style={myData.length > 0 ? hasData : noData}
                            title={ title }
                            data={myData}//this is your state
                            isFollowing={ isFollowing }
                            onToggleFollow={ id ? () => toggleSourceFollow(id, isFollowing, title) : null }
                            setListRef={ this.setListRef }
                            contentType="source"
                        />
                    );
    ```