【问题标题】:How can I send image in react-native-gifted-chat?如何在 react-native-gifted-chat 中发送图像?
【发布时间】:2020-12-31 15:04:25
【问题描述】:

我想在 react-Native-Gifted-chat 中发送图像,就像发送文本一样。我是 react-native 的新手。

我已经使用 react-native-image-picker 从物理设备中选择图像,现在我无法在 message[] 中渲染图像。

【问题讨论】:

    标签: react-native react-native-image-picker react-native-gifted-chat


    【解决方案1】:

    您可以调用 GiftedChat 的 onSend 方法,并以对象为参数。只需传递一个以图像为键的对象。例如

    onSend({ image: "https://picsum.photos/id/237/200/300" });
    

    【讨论】:

    • 非常感谢您的回答,但我有点困惑,请您描述一下如何使用 on-send 方法发送图像。我正在使用renderActions() 来处理handleImage ref.(github.com/FaridSafi/react-native-gifted-chat/issues/1745),但我仍然无法发送图像和渲染,我也使用renderMessageImage() 来渲染图像,但我没有成功。请帮帮我。
    【解决方案2】:

    你可以用这个 从“react-native-document-picker”导入 DocumentPicker;

    1. 先安装这个库

    2. 然后只需从文档选择器中选择文件 使用这个功能

      onAttatchFile = async () => { 尝试 { const res = await DocumentPicker.pick({ 类型:[DocumentPicker.types.allFiles], });

         // console.log(res);
         let type = res.name.slice(res.name.lastIndexOf('.') + 1);
         if (
           res.type == 'doc' ||
           res.type == 'application/pdf' ||
           res.type == 'image/jpeg' ||
           res.type == 'image/png' ||
           res.type == 'image/jpg' ||
           res.type == 'application/msword' ||
           type == 'docx'
         ) {
           this.setState({slectedFile: res}, () => this.onSendWithImage());
         } else {
           alert(`${type} files not allowed`);
         }
       } catch (err) {
         //Handling any exception (If any)
         if (DocumentPicker.isCancel(err)) {
           //If user canceled the document selection
           // alert('Canceled from single doc picker');
         } else {
           //For Unknown Error
           // alert('Unknown Error: ' + JSON.stringify(err));
           throw err;
         }
       }
      

      };

    3. 当您要发送图像时使用此功能

        onSendWithImage() {
      
       let imageData = {
         name: this.state.slectedFile.name,
         type: this.state.slectedFile.type,
         size: this.state.slectedFile.size,
         uri: this.state.slectedFile.uri,
       };
       var formData = new FormData();
       formData.append('type', 2);
       formData.append('senderId', this.state.senderData.id),
       formData.append('recieverId', this.state.reciverData._id),
       formData.append('message', imageData);
      
      
       post('sendMessage', formData).then(res =>
      
          res.success ? this.msjSendSuccess(res) : this.msjSendFailure(res),
       );
      

      }

    4. 与您的后端交谈并告诉他/她发送图像密钥中的图像

    5. 完全享受 React Native

    【讨论】: