【问题标题】:Unable to insert an image in Quill editor in react-native-webview无法在 react-native-webview 的 Quill 编辑器中插入图像
【发布时间】:2021-04-08 18:55:47
【问题描述】:

我的目标是在 Quill 编辑器 中的 react-native-webview 组件中插入图像,如下所示。为此,我需要访问脚本标记中的 quill 变量:

 <WebView
    originWhitelist={['*']}
    ref={(r) => setWebref(r)}
    javaScriptEnabled={true}
    source={{
      html: `<head>
              <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
              <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
             </head>
             <body>
              <div id="editor" >${content}</div>
             </body>
             <script> 
              var toolbarOptions = [[ 'bold', 'italic',],];
              var quill = new Quill('#editor', {
              modules: {
                toolbar: toolbarOptions
              })
            </script>`,
    }}
  />

当我尝试在 react-native 中在 webview 之外运行以下 sn-p 时,什么都没有发生

  const url = `https://...`;
  const code = `const range = window.quill.getSelection();
               window.quill.insertEmbed(range.index, 'image', ${url});
              `;
  webref.injectJavaScript(code);

但是,当我尝试在 react-native 中在 webview 之外运行以下 sn-p 时,我得到了预期的结果。

 const snippet = `document.body.style.backgroundColor = 'blue';
                  true; 
                 `;
 webref.injectJavaScript(snippet);

【问题讨论】:

  • 只是一个观察。你不需要像'${url}' 这样的${url} 周围的引号吗?
  • 没有。它已经引用了。从 const 范围开始。
  • 您是否尝试将其更改为我的建议?因为从我看到的const url = `https://blah.com`;const code = `....insertEmbed(range.index, 'image', ${url});`; 来看,注入代码的最终结果将是.insertEmbed(range.index, 'image', https://blah.com);它已经在引号中了 nop。它在反引号中,这使它成为template string literal
  • 谢谢你,@RomeoSierra!有效。你能把这个写成答案吗?

标签: android react-native quill react-native-webview


【解决方案1】:

问题出在

const url = `https://...`;
const code = `const range = window.quill.getSelection();
               window.quill.insertEmbed(range.index, 'image', ${url});
              `;

当您拥有const url = `https://blah.com`;const code = `....insertEmbed(range.index, 'image', ${url});`; 时,注入代码的最终结果将是...insertEmbed(range.index, 'image', https://blah.com);,在JavaScript 引擎看来这是一个语法错误。这些反引号分隔的字符串称为template string literals,用于格式化字符串。因此,为了使您的代码块正常工作,应按如下方式进行更正。

const url = `https://...`;
const code = `const range = window.quill.getSelection();
               window.quill.insertEmbed(range.index, 'image', '${url}');
              `; //NOTICE THE SINGLE QUOTES AROUND ${url}

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2018-05-31
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    相关资源
    最近更新 更多