2017-10-21 121 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()} 

所以,你可以访问你的类上下文。