首页 > 解决方案 > 异步 React Native 的按钮无响应问题

问题描述

我从 github 项目中复制了闲置代码并尝试使用 expo。该项目执行没有错误,但是当我按下按钮时没有任何反应。甚至没有错误这是我的代码 NB-我在 onChooseImagePress 中设置了一个警报并且警报工作正常

import React from 'react';
import { Image, StyleSheet, Button, Text, View, Alert, } from 'react-native';
import { ImagePicker } from 'expo';
import * as firebase from 'firebase';
import {firebaseConfig} from "./ApiKeys";

export default class HomeScreen extends React.Component {
    static navigationOptions = {
        header: null,
    };

    onChooseImagePress = async () => {
        let result = await ImagePicker.launchCameraAsync();
        //let result = await ImagePicker.launchImageLibraryAsync();

        if (!result.cancelled) {
            this.uploadImage(result.uri, "test-image")
            .then(() => {
                Alert.alert("Success");
            })
            .catch((error) => {
                Alert.alert(error);
            });
        }
    }

    uploadImage = async (uri, imageName) => {
        const response = await fetch(uri);
        const blob = await response.blob();

        var ref = firebase.storage().ref().child("images/" + imageName);
        return ref.put(blob);
    }

    render() {
        return (
            <View style={styles.container}>
            <Button title="Choose image..." onPress={this.onChooseImagePress} />
            </View>
            );
        }
    }

    const styles = StyleSheet.create({
        container: { flex: 1, paddingTop: 50, alignItems: "center", },
    });
}

标签: androidiosreact-nativeexpo

解决方案


尝试使用下面的代码

constructor() {
    super();
    this.state = { }; 
    this.onChooseImagePress= this.onChooseImagePress.bind(this);

  } 

<Button title="Choose image..." onPress={() => this.onChooseImagePress()} /> 

推荐阅读