与条件反应本机listview

时间:2018-10-23 07:55:46

标签: listview react-native

如果要在react native的listview内部使用,我想使用conditon,我的代码是:

    constructor(props) {
      super();
      const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
      this.state = {
        dataSource: ds.cloneWithRows(props.data)
      };
      console.log(props.data)
    }    
render()
{
return (
<ListView
dataSource ={this.state.dataSource}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
renderRow={(rowData) => 
<TouchableOpacity style={{backgroundColor:'#fbeded'}}>
<Text style={{textAlign:'right',alignItems:'flex-end',width:'100%',fontSize:18,paddingTop:10,marginRight:'15%',fontFamily:"B Nazanin+ Bold"}}>{rowData.name}</Text>
<View  style={styles.separator1} />
//how use this condition in listview 
if({rowData.address} !==null)
{
<View style={{flexDirection:'row'}}>
<Text style={{textAlign:'right',width:'90%',alignItems:'flex-end',fontSize:18,marginRight:10,marginTop:10,fontFamily:"B Nazanin+ Regular"}}>address
:{rowData.province_name}- {rowData.city_name}- {rowData.address}</Text>
<Icon style={{width:'5%',height:'100%',marginTop:10}}
  name='place'
  color='red'
  />
</View>
}
else
{
<View style={{flexDirection:'row'}}>
<Text style={{textAlign:'right',width:'90%',alignItems:'flex-end',fontSize:18,marginRight:10,marginTop:10,fontFamily:"B Nazanin+ Regular"}}>address
:{rowData.province_name}- {rowData.city_name}- {rowData.address}</Text>
<Icon style={{width:'5%',height:'100%',marginTop:10}}
  name='place'
  color='blue'
  />
}
</TouchableOpacity> 
}
/>)
} 

我将if..else更改为?:条件,但无法在列表中显示我的条件,并且无法一起显示if和else。

3 个答案:

答案 0 :(得分:0)

通常,条件渲染使用? :完成。像这样:

<View> { (condition) ? <Text>Yes</Text> : <Text>No</Text> } </View>

如果这不是您想要的,请在问题中阐明您的要求

答案 1 :(得分:0)

就像我在下面所做的那样,您可以使用条件运算符来使用条件渲染,而不是if else块。

如果条件为true,则第一个块将在“:”之后执行,否则将执行。

 {
  (rowData.address.trim() != "" ) ? 
   <View style={{flexDirection:'row'}}>
   <Text 
     style={{textAlign:'right',width:'90%',alignItems:'flexend',fontSize:18,marginRight:10,
     marginTop:10,fontFamily:"B Nazanin+ Regular"}}
   >
   address:{rowData.province_name}- {rowData.city_name}- {rowData.address}
   </Text>
  <Icon 
    style={{width:'5%',height:'100%',marginTop:10}}
    name='place'
    color='red'
   />
  </View>
  :
<View style={{flexDirection:'row'}}>
<Text style={{textAlign:'right',width:'90%',alignItems:'flex-end',fontSize:18,marginRight:10,marginTop:10,fontFamily:"B Nazanin+ Regular"}}>address
:{rowData.province_name}- {rowData.city_name}- {rowData.address}</Text>
<Icon style={{width:'5%',height:'100%',marginTop:10}}
  name='place'
  color='blue'
  />

}

答案 2 :(得分:0)

您应该将列表项导出到单独的组件中,并在返回之前在渲染器中编写if和else语句。