【问题标题】:Unable to access quill instance within a module function无法访问模块函数中的 quill 实例
【发布时间】:2021-08-04 03:44:41
【问题描述】:

我有:

    const formats = ['header', 'bold', 'italic', 'underline', 'list', 'prediction', 'accepted', 'mention'];
    const modules = {
        mention: {
            allowedChars: /^[a-zA-Z0-9_]*$/,
            mentionDenotationChars: ['@'],
            showDenotationChar: false,
            spaceAfterInsert: false,
            onSelect: (item, insertItem) => {
                clearDocumentState(0)
                const cursorPos = quill.getSelection()
                console.log({ cursorPos })
                insertItem(item)
            },
            source: () => { }
        },
        toolbar: [
            ['bold', 'italic', 'underline'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ header: [1, 2, false] }],
            ['clean']
        ]
    };

    const { quill, quillRef, Quill } = useQuill({
        formats,
        modules,
        placeholder: 'Start writing something amazing...'
    });

如果重要的话,我正在使用https://github.com/afry/quill-mention 和https://github.com/gtgalone/react-quilljs。

当我尝试在onSelect 函数中访问quill 实例时,我得到:

TypeError: Cannot read property 'getSelection' of undefined

我假设函数被缓存了,quill 还没有定义。有什么方法可以得到那个实例?

【问题讨论】:

  • 不确定 quill 是什么,但您是否尝试将 useQuill 放在模块声明之上?
  • 我不能因为在定义quill时需要modules
  • 并且没有办法将您的提及模块注册到具有 quill 依赖项的 useEffect 上,所以如果它存在,那么您注册“提及”模块?

标签: javascript reactjs closures quill


【解决方案1】:

当 quill 有值时,您可以在 useEffect 块中设置 onSelect 回调。使用getModule获取mention模块并设置对应的option:

 React.useEffect(() => {
    if (quill) {
      quill.getModule('mention').options.onSelect = ((item, insertItem) => {
        clearDocumentState(0);
        const cursorPos = quill.getSelection();
        console.log({ cursorPos });
        insertItem(item);
      });
    }
  }, [quill]);

Working example

【讨论】:

    猜你喜欢
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    相关资源
    最近更新 更多