【问题标题】:Implement onPress on Flatlist item在 Flatlist 项目上实现 onPress
【发布时间】:2019-11-27 10:22:22
【问题描述】:

我正在尝试在单击并设置为另一个类时发送平面列表项的数据。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>

    );
}
}

【问题讨论】:

    标签: react-native-android react-native-flatlist


    【解决方案1】:

    您的代码中的问题是,您从两侧调用相同的方法 - 一方面您在其中传递参数,另一方面您没有传递参数。如果您不想同时涵盖这两种情况,则应更改 onPressFunction,以接受参数 - 在您的情况下 item

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        • 2023-03-27
        • 2019-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多