2017-10-21 116 views
0

首先,我使用圖像選取器來獲取圖像和RNFetchBlob以在API中發送。 我的問題是,我有一些文本輸入,並在最後推按鈕,我想同時發送這個輸入與圖像。爲此,我試圖保存圖像uri作爲狀態發送。但似乎_this2.setState不是一個函數。目前我不知道如何解決它。React-native將圖像保存爲狀態不起作用

這是我的代碼簡化。

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); 
    }) 
    } 
    }) 
    } 

} 
+0

你需要將'this'與你的函數綁定。看看[處理事件](https://reactjs.org/docs/handling-events.html) – bennygenel

+0

謝謝!現在正在工作 –

回答

2

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

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

所以,你可以訪問你的類上下文。