【问题标题】:How can I attach word/pdf files to React Native gifted chat?如何将 word/pdf 文件附加到 React Native 天才聊天?
【发布时间】:2021-09-18 20:43:06
【问题描述】:

我希望能够使用 react native 天才聊天功能,在我的 react native 应用程序中通过消息发送 word doc/pdf 文件。我查看了一些链接,这些链接建议在 react-native-gifted-chat 中使用 renderActions() 函数,但它没有指定我如何实现这一点。你知道我如何实现这个功能吗?我需要在函数中导入像文档选择器或文件选择器这样的包吗?如果是这样,我该如何使用它?我对本机反应还很陌生。有人可以帮忙吗?

这是我目前的 renderActions() 方法中的内容:

renderActions() {
    return(
           <Actions
           {...props}
           options={{
        ['Document']: async (props) => {
                       try {
                         const result = await DocumentPicker.pick({
                           type: [DocumentPicker.types.doc || DocumentPicker.types.docx || DocumentPicker.types.pdf],
                         });                   
                         console.log("resulting file: "+result);
                         console.log("string result? "+JSON.stringify(result));
                       } catch(e){
                           if(DocumentPicker.isCancel(e)){
                             console.log("User cancelled!")
                           } else {
                             throw e;
                          }
                        }

                       },
        ['Cancel']: (props) => {console.log("cancel")}
           }}
           icon={() => (
              <Ionicons
                  name={'add'}
                  size={28}
                  color={'#0077ff'}
                  style={{left:0, bottom:0}}
                        
              />
            )}
           onSend={args => console.log(args)}
           />
    )
    
}

产生:

我已经设法得到文件对象。有谁知道一旦选择了我如何将此文档文件对象附加到有天赋的聊天中的消息中?有人可以帮忙吗?如何在聊天框中显示然后发送文件?

谢谢。

链接https://github.com/FaridSafi/react-native-gifted-chat/issues/2111 提到要向消息对象添加参数。例如你有这个消息对象:

 const newMessage = {
    _id: data.send_at,
    text: data.messagetext,
    createdAt: data.send_at,
    (...),
    file_type: data?.file_type,
    file_id: data?.file_id,
 }

然后渲染一个自定义视图:

 const renderCustomView = (props) => {
   if (props?.currentMessage?.file_type) {
    (...)
   }
   else {
    (...)
   }
 }

有人可以帮忙说明我需要在哪里创建消息对象以及我需要在 renderCustomView 函数中放置什么吗?我真的不太确定需要做什么。

【问题讨论】:

  • 有人可以帮忙吗?我真的很感激。
  • JPithwa 或其他人可以为此stackoverflow.com/questions/63314582/… 发布解决方案吗?
  • 有人可以帮忙吗?我已经设法使用 react-native-document-picker 选择了一个文档文件,但我不确定如何将它附加到有天赋的聊天对象中,以便我可以在聊天框中显示它并发送。请帮忙。谢谢

标签: firebase react-native firebase-realtime-database firebase-storage react-native-gifted-chat


【解决方案1】:
function renderActions(props) {
let selectFile = async () => {
  //Opening Document Picker to select one file
  try {
    const res = await DocumentPicker.pick({
      //Provide which type of file you want user to pick
      type: [DocumentPicker.types.pdf],
      //There can me more options as well
      // DocumentPicker.types.allFiles
      // DocumentPicker.types.images
      // DocumentPicker.types.plainText
      // DocumentPicker.types.audio
      // DocumentPicker.types.pdf
    });
    //Printing the log realted to the file
    console.log('res : ' + JSON.stringify(res));
    props.onSend({pdf:res.uri,file_type:'pdf'});
    //Setting the state to show single file attributes
    singleFile = res;
    // setSingleFile(res);
  } catch (err) {
    singleFile = null;
    // setSingleFile(null);
    //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;
    }
  }
};
const handlePicker = () => {
  // console.log('edit');
  ImagePicker.showImagePicker({}, (response) => {
    // console.log('Response = ', response);

    if (response.didCancel) {
      console.log('User cancelled image picker');
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
    } else {
      setAvatar({uri: response.uri});
      console.log(response.uri);
      props.onSend({image:response.uri});
    //   onSend([{"_id": "f3fda0e8-d860-46ef-ac72-0c02b8ea7ca9", "createdAt": new Date(), "image": response.uri, "user": {"_id": 1}}])
      return response.uri
      // here we can call a API to upload image on server
    }
    return avatar;
  });
};

return (
  <Actions
    {...props}
    options={{
      ['Send Image']: () => handlePicker(),
      ['Send Files']: () => selectFile(),
    }}
    icon={() => (
      <Icon name='attachment' size={28}  />
    )}
    // onSend={onSend}
  />
)}

在自定义视图中:

export default class CustomView extends React.Component {
  
  renderPdf() {
      return (
        <TouchableOpacity style= 
            {[styles.container,this.props.containerStyle]} >
      <Image
          {...this.props.imageProps}
         style={[styles.image, this.props.imageStyle]}
         source ={{
                 uri:""
              }}
     />
    </TouchableOpacity>
    );
  }



render() {
  if (this.props.currentMessage.file_type == 'pdf') {
     return this.renderPdf();
  } else if (this.props.currentMessage.template && 
       this.props.currentMessage.template != 'none') {
     return this.renderHtml();
   }
    return null;
  }
 }

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
  • 2016-08-18
  • 2018-08-31
相关资源
最近更新 更多