在列表项中反应本机条件onPress

时间:2018-08-17 13:45:11

标签: javascript react-native

我在React native中用List项生成一个列表,出于特定原因,我希望第一个项导航到另一个屏幕,而所有其他项导航到另一个屏幕。

我用三元运算符设置条件,但没有成功

<View style={{flex: 1, backgroundColor: '#fff'}}>
                    <List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
                    <FlatList
                        data={this.state.schools}
                        renderItem={({ item }) => ({
                        item.school_name == "all" ?
                        <ListItem
                            title={item.school_name}
                            onPress={()=>this.props.navigation.navigate('DepartmentSchools', {
                                school_name: item.school_name,
                                school_id : item.school_id
                            })}
                        /> : 
                        <ListItem
                            title={item.school_name}
                            onPress={()=>this.props.navigation.navigate('DepartmentIndividual', {
                                school_name: item.school_name,
                                school_id : item.school_id
                            })}
                        />
                        })}
                        keyExtractor={item => item.school_name}
                        ItemSeparatorComponent={this.renderSeparator}
                    />
                    </List>
                    </View>

请帮助解决此问题,否则您可以指出我的错误。

先谢谢了。

1 个答案:

答案 0 :(得分:1)

像这样将条件移动到onPress处理程序:

 <FlatList
       data={this.state.schools}
       renderItem={({ item }) => (
                    <ListItem
                        title={item.school_name}
                        onPress= {
                          ()=>{
                             let destination = item.school_name === "all" ? "DepartmentSchools" : "DepartmentIndividual";
                             this.props.navigation.navigate(destination, {
                                school_name: item.school_name,
                                school_id : item.school_id
                             });
                           }
                        }
                    />
                  )}
      keyExtractor={item => item.school_name}
      ItemSeparatorComponent={this.renderSeparator}
   />