英文:
How to pass events in the SLATEJS rich text editor
问题
I'm trying coding follow this doc:
https://docs.slatejs.org/walkthroughs/05-executing-commands
I just wanted to make it elegant, so I tried to separate the Toolbar Button into other files. But how do I pass the event onKeydown there?
I tried the following code, but I got the result that 'editor is undefined'
Did I overlook something?
Here is a simple DEMO:
exprot function App(){
//...others
const [editor] = useState(() => withReact(createEditor()));
return (
<Slate {...props} >
<MyToolbar {...editor} />
//...others
</Slate>
);
}
function MyToolbar(editor: ReactEditor){
return (
<div>
//Icon button span
<span {...props} onMouseDown={event => {
event.preventDefault();
CustomEditor.toggleBold(editor);
}}></span>
</div>
);
}
(Note: The code appears to have some HTML encoding issues with '<' and '>' characters, which need to be corrected to make it work.)
英文:
I'm trying coding follow this doc:
https://docs.slatejs.org/walkthroughs/05-executing-commands
I just wanted to make it elegant, so I tried to separate the Toolbar Button into other files. But how do I pass the event onKeydown there?
I tried the following code, but I got the result that 'editor is undefined'
Did I overlook something?
Here is a simple DEMO:
exprot function App(){
//...others
const [editor] = useState(() => withReact(createEditor()));
return (
<Slate {...props} >
<MyToolbar {...editor} />
//...others
</Slate>
);
}
function MyToolbar(editor: ReactEditor){
return (
<div>
//Icon button span
<span {...props} onMouseDown={event => {
event.preventDefault();
CustomEditor.toggleBold(editor);
}}></span>
</div>
);
}
答案1
得分: 1
不要将editor
作为一个属性传递,使用钩子useSlate()
来获取它:
import { useSlate } from "slate-react";
function MyToolbar() {
const editor = useSlate();
return (
<div>
<span
onMouseDown={event => {
event.preventDefault();
CustomEditor.toggleBold(editor);
}}
></span>
</div>
);
}
英文:
Don't pass editor
as a prop, use the hook useSlate()
to get it:
import { useSlate } from "slate-react";
function MyToolbar() {
const editor = useSlate();
return (
<div>
<span
onMouseDown={event => {
event.preventDefault();
CustomEditor.toggleBold(editor);
}}
></span>
</div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论