You need to enable JavaScript to run this app. 如何在React Native项目的Quill编辑器工具栏中添加自定义图标
优惠活动
大模型
产品
解决方案
定价
更多

如何在React Native项目的Quill编辑器工具栏中添加自定义图标

React Native 集成Quill添加自定义工具栏图标解决方案

1. 调整quill.html配置,新增自定义图标样式与交互逻辑

修改后的完整quill.html代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <style>
      html,body {
        height: 100%;
        width: 100%;
        margin: 0;
        padding: 0;
        background-color:rgba(0, 0, 0, 0);
      }
      #editor {
        height: calc(100% - 72px);
        background-color:rgba(0, 0, 0, 0);
      }
      /* 自定义按钮样式 示例为插入时间按钮 */
      .ql-custom-time::before {
        content: '⏰';
        font-size: 18px;
      }
      /* 多按钮可继续新增对应样式 */
    </style>
    <link rel="stylesheet" type="text/css" href="https://cdn.quilljs.com/1.3.7/quill.snow.css"></link>
  </head>
  <body>
    <div id="editor"></div>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.7/quill.min.js"
      integrity="sha512-P2W2rr8ikUPfa31PLBo5bcBQrsa+TNj8jiKadtaIrHQGMo6hQM6RdPjQYxlNguwHz8AwSQ28VkBK6kHBLgd/8g=="
      crossorigin="anonymous"
      referrerpolicy="no-referrer"
    ></script>
    <script>
      const quill = new Quill('#editor', window.options);
      // 注册自定义按钮的点击处理逻辑
      const toolbar = quill.getModule('toolbar');
      toolbar.addHandler('custom-time', function() {
        // 示例:直接在光标位置插入当前时间
        const range = quill.getSelection();
        if (range) {
          const timeText = new Date().toLocaleString();
          quill.insertText(range.index, timeText);
          quill.setSelection(range.index + timeText.length, 0);
        }
        // 若需要和RN侧交互,可通过postMessage传递事件
        // window.ReactNativeWebView.postMessage(JSON.stringify({
        //   type: 'customTimeClick',
        // }));
      });
      quill.on('text-change', function (delta, oldDelta, source) {
        const html = document.querySelector('#editor').children[0].innerHTML;
        const message = {
          type: 'onChange',
          message: html,
        };
        window.ReactNativeWebView.postMessage(JSON.stringify(message));
      });
    </script>
  </body>
</html>

2. 修改QuillEditor.tsx,将自定义按钮加入工具栏配置

修改工具栏默认配置,新增自定义按钮标识符:

import React, { useRef } from 'react'
import { Dimensions, Platform, ViewStyle } from 'react-native'
import { WebView, WebViewMessageEvent } from 'react-native-webview'

type Props = {
  style?: ViewStyle
  defaultValue?: string
  options?: any
  onChange?: (html: string) => void
  // 可选:新增自定义按钮点击回调props
  onCustomTimeClick?: () => void
}

// 工具栏配置新增自定义按钮标识
const defaultValue = [[{ header: [1, 2, false] }], ['bold', 'italic', 'underline'], ['image', 'code-block'], ['custom-time']];

const Quill = (props: Props) => {
  const webviewRef = useRef<WebView>(null);
  const options = JSON.stringify({
    placeholder: 'Type here...',
    modules: {
      toolbar: defaultValue,
    },
    ...props.options,
    theme: 'snow',
  })
  const injectedJavaScriptBeforeContentLoaded = `window.options=${options}`
  const injectedJavaScript = `document.querySelector('#editor').children[0].innerHTML="${props.defaultValue}"`

  const onMessage = (e: WebViewMessageEvent) => {
    const data = JSON.parse(e.nativeEvent.data)
    if (data.type === 'onChange') {
      props.onChange(data.message)
    }
    // 接收quill侧的自定义按钮点击事件,触发RN侧回调
    if (data.type === 'customTimeClick') {
      props.onCustomTimeClick?.()
      // 示例:RN侧处理完逻辑后,可通过injectJavaScript往quill插入内容
      // webviewRef.current?.injectJavaScript(`
      //   const range = quill.getSelection();
      //   quill.insertText(range.index, "RN侧传入的内容");
      // `)
    }
  }

  return (
    <WebView
      ref={webviewRef}
      onMessage={onMessage}
      source={Platform.OS === 'ios' ? require('../../assets/quill.html') : { uri: 'file:///android_asset/quill.html' }}
      javaScriptEnabled
      injectedJavaScriptBeforeContentLoaded={injectedJavaScriptBeforeContentLoaded}
      injectedJavaScript={injectedJavaScript}
      style={{ height: Dimensions.get('window').height - 42, width: Dimensions.get('window').width, ...props.style }}
    />
  )
}

Quill.defaultProps = {
  style: {},
  defaultValue: '',
  onChange: () => {},
  options: {},
  onCustomTimeClick: () => {},
}

export default Quill

3. 自定义图标资源方案

若需使用自定义图片图标,可将图标转为Base64编码,直接写入quill.html的CSS中,无需引入外部资源:

.ql-custom-image::before {
  content: '';
  display: inline-block;
  width: 18px;
  height: 18px;
  background-image: url('data:image/png;base64,这里替换为你的图标Base64编码');
  background-size: cover;
}

多自定义按钮可按照上述逻辑,新增对应CSS样式、Handler处理逻辑、工具栏配置即可。

内容的提问来源于stack exchange,提问作者Shivam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 07:54:01