如何在 Flatlist 中使用 onPress

How to use onPress with a Flatlist

我正在尝试在 React Native 中构建一个 FlatList。我遇到的问题是 onPress 道具并试图让它与 FlatList 一起工作。问题是列表中的每个项目都会触发 onPress,而不是我专门按下的项目。

这是我组件中的Flatlist

           <FlatList
              data = {this.state.dataSource}
              renderItem = {({item}) => <PickerBox title = {item.c_syn_name} onPress = {this._onPress(item.c_syn_name)} />}
              keyExtractor = {(item, index)=> item.c_syn_name}
              backgroundColor = "thistle"

            />

这是 PickerBox 组件:

    const styles = StyleSheet.create({
      container: {
        flex: 1,
        flexDirection: "row",
        padding: 10,
        marginLeft: 16,
        marginRight: 16,
        marginTop: 8,
        marginBottom: 8,
        borderRadius: 5,
        backgroundColor: "slategrey",
        elevation: 2
      },
      shadow: {
        flex: 1,
        flexDirection: "row",
        padding: 0,
        marginLeft: 16,
        marginRight: 16,
        marginTop: 8,
        marginBottom: 8,
        borderRadius: 5,
        backgroundColor: "darkslategray",
        elevation: 2
      },
      title: {
        fontSize: 16,
        color: "#000"
      },
      container_text: {
        flex: 1,
        flexDirection: "column",
        marginLeft: 12,
        color: "#FFF"
      },
      description: {
        fontSize: 11,
        fontStyle: "italic"
      }
    });

    class PickerBox extends Component<props> {
      render() {
        const { title } = this.props;
        return (
          <View style={styles.shadow}>
            <View style={styles.container}>
              <Text
                style={styles.container_text}
                onPress={() => this.props.onPress}
              >
                {title}
              </Text>
            </View>
          </View>
        );
      }
    }
    export default PickerBox;

这是我的 onPress 函数,它位于包含我的平面列表的组件中,并通过 PickerBox 函数中的 props 传递:

    _onPress = newName => {
        this.setState({ newTaxon: newName });
        Alert.alert("New Taxon: "+this.state.newTaxon.toString());
    };

行为是 Alert 会出现在每个列表项上,而它应该只出现在我特别按下的项目上。

您正在 renderItem 中的这一行立即调用 onPress 回调:

onPress = {this._onPress(item.c_syn_name)}

表示onPress得到_onPress的结果。这就是为什么您每次都会收到该警报弹出窗口的原因。您需要为 onPress 提供要调用的函数。一个简单的方法就是做这样的事情:

onPress={() => this._onPress(item.c_syn_name)}

通过将其包装在箭头函数中,_onPress 不会在呈现 FlatList 时立即调用。 _onPress 的值现在是一个可以调用的函数。

const Main = () => {
    <FlatList
       data={[
          {id: 1, title: one},
          {id: 2, title: two}
         ]}
       keyExtractor={(item) => item.id.toString()}
       renderItem={({item}) => (
          <Card 
           onPress={() => yourFunction()}
           title={item.label}
          />
        }
     />
 }



const Card = ({ onPress, title }) => {
    <View onPress={onPress}>
      <Text>{title}</Text>
    </View>
}