React Native Gifted Chat 中渲染 Markdown 消息

文章目录

    晚上实现了 React Native Gifted Chat 中渲染 Markdown 消息,折腾完之后,我甚至感觉 React Native 的库比 React 的库都可靠。

    安装依赖

    https://www.npmjs.com/package/react-native-markdown-display

    npm install react-native-markdown-display
    

    会看到安装了最新版本的依赖

    git diff .\package.json
    
    +    "react-native-markdown-display": "^7.0.2",
    

    是否支持 web

    主要是被官方介绍吓到了:

    It a 100% compatible CommonMark renderer, a react-native markdown renderer done right. This is not a web-view markdown renderer but a renderer that uses native components for all its elements. These components can be overwritten and styled as needed.

    我以为不支持 web view。

    从

    npm run web
    

    的演示结果看,是支持 web 的。

    如何渲染返回信息中的 markdown 内容

    新增一个自定义的 renderMessageText 方法,然后在新建的 message 消息中,增加一个 markdown 字段,bool 类型。
    如果这个值为真,就进入 markdown 的渲染逻辑:

    import { GiftedChat, MessageText } from 'react-native-gifted-chat'
    import { Platform, View, Text } from 'react-native'
    import Markdown from 'react-native-markdown-display'
    
    +  const renderMessageText = (props: any) => {
    +    const { currentMessage } = props
    +    if (currentMessage.markdown) {
    +      return (
    +        <View>
    +          <Markdown>{currentMessage.text}</Markdown>
    +        </View>
    +      )
    +    }
    +    return <MessageText {...props} />
    +  }
    +
       return (
         <GiftedChat
           messages={messages}
           onSend={msgs => onSend(msgs)}
           user={user}
           onQuickReply={handleQuickReply}
    +      renderMessageText={renderMessageText}
         />
       )
     }
    

    如何跟 github copilot 合作

    这是第一次比较完整的跟 github copilot 合作完成一个功能的案例,所以有必要记录一下。
    之前都是大部分靠自动补全实现的。而这次靠补全是很难完成的,看来 copilot pro 充值还是物有所值的。

    完整的提问过程:

    1. 如何渲染返回的 custom 信息中的 markdown 内容
    2. 上面的实现有点问题,会把所有消息都当作 markdown 处理。而我需要的是对某些特定消息做 markdown 渲染
    3. renderMessageText 如何沿用默认的样式

    如果采用习惯性的做法,会先去 Google 找 React Native 支持 Markdown 渲染的库。
    但是搜索结果优先推荐了一个多年不维护的库,而直接问 github copilot 则会推荐一个更为活跃,也更多采用的上面这个库。

    再就是,第一次提问,给出的解决方案,并不好。因为没有考虑到其他消息类型。

    我第一反应是,继续去 google 搜索,自己寻求答案。但是,期间我去打洗脚水,突然相对,为何不能继续引导 AI 给出更合理的解决方案呢?

    于是又出现了后面第二个,第三个问题。最后给出的代码就能直接使用了。非常棒。

    阅读更多 👀

    React Native 跨平台应用开发教程