Implement onPress on Flatlist item

人盡茶涼 提交于 2019-12-11 17:05:01

问题


I am trying to send the data of the flatlist items when clicked and set to another class.The ontouch is working but I am having the error below in the image. Also how can I send the data of api to the other class and get from another class? I have implemented as follows:

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>

    );
}
}

回答1:


Problem in your code is, that you are calling same method from two sides - on one side you are passing arguments in it on another side you are not passing arguments. If you wan't to have both cases covered you should change you onPressFunction, to accept arguments - in your case item:

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



回答2:


try to put this.onPressItem = this.onPressItem.bind(this) on constructor(props)



来源:https://stackoverflow.com/questions/59067932/implement-onpress-on-flatlist-item

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