簡體   English   中英

反應本機保存圖像為狀態不起作用

[英]React-native saving image as state not working

首先,我正在使用Image Picker獲取圖像並將RNFetchBlob發送到API中。 我的問題是我有一些文本輸入,最后按下一個按鈕,我想同時發送此輸入和圖像。 為此,我嘗試將圖像uri保存為狀態以在以后發送。 但是出現_this2.setState不是一個函數。 目前,我不知道如何解決。

這是我的簡化代碼。

class Create extends Component{

  constructor(props){
    super(props);
    this.state = {
      foto: '',
    }     
  }

openImagePicker(){
  const options = {
    title: 'Select Avatar',
     storageOptions: {
      skipBackup: true,
      path: 'images'
                     }
  }

  ImagePicker.showImagePicker(options, (imagen) =>{
      if (imagen.didCancel) {
    console.log('User cancelled image picker');
  }
  else if (imagen.error) {
    console.log('ImagePicker Error: ', imagen.error);
  }
  else if (imagen.customButton) {
    console.log('User tapped custom button: ', imagen.customButton);
  }
  else {
    let source = { uri: imagen.uri };
    console.log(source.uri);
    this.setState({
        foto: source.uri
      })    
 }

render(){
        return(     
    <Container>
        <Header><Title>Eat</Title></Header>
        <Content>
            <Text>Título</Text>
            <View>
              <TextInput  
                onChangeText={(text) => this.titulo = text}   
              />
            </View>
            <Text>Personas</Text>
            <View style={styles.container}>
              <TextInput               
                type="number" 
                onChangeText={(text) => this.personas = text}   
              />
            </View>
            <Text>Foto</Text>
            <View>
            <TouchableOpacity activeOpacity={.8} onPress={this.openImagePicker}>
                <View>
                  <Text>Cambiar</Text>
                </View>
            </TouchableOpacity>
            </View>
            <View>
            <ScrollView >
            <TouchableHighlight onPress={(this._create.bind(this))}>
                <Text>Crear Receta</Text>
            </TouchableHighlight>
            </ScrollView>
            </View>
        </Content>
    </Container>
                )
    }

_create () {


 RNFetchBlob.fetch('POST', 'XXXXXXXXXXXX', {
    'Content-Type' : 'multipart/form-data',
    },
   [
    // element with property `filename` will be transformed into `file` in form data
    { name : 'file', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(source.uri)},
    { name : 'info', data : JSON.stringify({
      "titulo": this.titulo,
      "personas": this.personas,
    })} 
  ]).then((resp) => {   
    console.log("ok");
  }).catch((err) => {
    console.log(err);
  })
    }
  })
  }

}

您可以綁定方法openImagePicker或這樣調用它:

onPress={() => this.openImagePicker()}

這樣您就可以訪問您的類上下文。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM