我有:
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如果重要的话。当我尝试访问
quill
onSelect
中的实例功能,我得到:TypeError: Cannot read property 'getSelection' of undefined
我假设函数被缓存了,quill
尚未定义。有什么办法可以得到那个实例?
最佳答案
您可以设置onSelect
useEffect
中的回调当 quill 有值时阻塞。使用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
关于javascript - 无法访问模块函数中的 quill 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67526328/