How to render something in an if statement React Native

╄→гoц情女王★ 提交于 2019-12-11 03:37:27

问题


Problem

I am using a flatlist in react native, and want to compare to variables in the flatlist, and render a text component if the two variables are equal, but render nothing if they are not. I've tried many methods of doing this, but they nothing has worked. I would love some help figuring out a way to do this! Thank you.


回答1:


Couple ways that spring to mind straight away. Ill just assume what you are trying to compare but you can switch these variables out for whatever you please. First thing you could do is have your text be conditional inside of your Text component, EG

<Text>{this.state.variable == this.props.stuff ? "RENDER TEXT" : ""}</Text>

or, if you want to emit the Text component when variables are not equal, have a function inside of your class that will return the Text component conditionally

renderMessage = () => {
    if(this.state.variable == "stuff"){
        return(
            <Text>They were equal</Text>
        );
    }else{
        return(
            <View></View> // OR WHATEVER YOU WANT HERE
        );
    }
}
...
//Then in your render function
....
<View style = {styles.whatever}>
    {this.renderMessage()}
</View>



回答2:


just compare your data in renderItem method accordingly

 <FlatList
      data={this.props.data}
      renderItem={this._renderItem}
    />

    _renderItem = ({item}) => (
        if(item=='somthing'){
           return <Text> your test </Text>
         }else{
            return <Text>some other text</Text> 
         }
    );

if you want to compare your text in component then

<View>
    {
    item.data == 'somthing'
       ?
      <Text>if</Text> 
       :
      <Text>else</Text>
    }
</View>


来源:https://stackoverflow.com/questions/47586437/how-to-render-something-in-an-if-statement-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!