在平面列表项上实现onPress

人气:54 发布:2023-01-03 标签: react-native-android react-native-flatlist

问题描述

我正在尝试在单击时发送平面列表项目的数据,并将其设置为另一个类。OnTouch正在工作,但我在图像中出现以下错误。另外,我如何将API的数据发送到另一个类并从另一个类获取?我的实现如下:

export default class FlatSpeakers extends Component {

constructor(props) {
    super(props);
    this.state = { isLoading: true, data: [],selectedItem: null, }
   const { navigate } = this.props.navigation;
}

onPressItem = () => {
  navigate('SpeakersClick')
};

componentDidMount() {
    axios.get('https://rallycoding.herokuapp.com/api/music_albums')
        .then(res => {
            this.setState({
                isLoading: false,
                data: res.data,
            })
        })
}

renderItem({ item }) {
    return (
        <TouchableOpacity onPress={()=>this.onPressItem(item)} >
            <Card>
                <CardSection>
                    <View style={styles.thumbnailContainerStyle}>
                        <Image
                            style={styles.thumbnailStyle}
                            source={{ uri: item.image }}
                        />
                    </View>
                    <View style={styles.headerContentStyle}>
                        <Text style={styles.headerTextStyle}>{item.title}</Text>
                        <Text>{item.artist}</Text>
                    </View>
                </CardSection>
            </Card>
        </TouchableOpacity>
    )
}

render() {
    if (this.state.isLoading) {
        return (
            <View style={{ flex: 1, padding: 20 }}>
                <ActivityIndicator />
            </View>
        )
    }

    return (
            <View style={styles.container}>
                <FlatList
                    data={this.state.data}
                    renderItem={this.renderItem}
                    keyExtractor={(item, index) => index}
                    onPress={this.onPressItem}
                />
            </View>

    );
}
}

推荐答案

尝试将this.onPressItem = this.onPressItem.bind(this)放在constructor(props)

14