[英]How to prevent select event from firing after every input?
I'm trying to create a custom text editor in React, thus I've created a div
which has a contentEditable
attribute.我正在尝试在 React 中创建自定义文本编辑器,因此我创建了一个具有
contentEditable
属性的div
。 Now I want to perform some action when the user selects a part of the inputted text.现在我想在用户选择输入文本的一部分时执行一些操作。 To do that I'm using the
select
event as onSelect
attribute on my div.为此,我将
select
事件用作我的 div 上的onSelect
属性。 The problem is that, select
event runs not only when selecting the text, but also when I click on the input box, or after any input.问题是,
select
事件不仅在选择文本时运行,而且在我单击输入框或任何输入后运行。 How can I prevent it, so that it gets fired only when the text is selected?我怎样才能阻止它,以便只有在选择文本时才会触发它?
Component:成分:
function EditorBody(props) {
return (
<div className="editor-body">
<div
className="text-section"
contentEditable
role="textbox"
placeholder="Text goes here ..."
onSelect={() => window.alert("You've selected a text")} // Runs after every input, not only when the text is selected
></div>
</div>
);
}
export default EditorBody;
You can change the logic in your onSelect
to be able to determine whether or not to execute the selected logic.您可以更改
onSelect
中的逻辑,以便能够确定是否执行所选逻辑。
onSelect={(event) => {
if (document.getSelection().toString().length > 0) {
// your selection logic
window.alert(document.getSelection().toString());
}
}}
This way the logic will be executed only if the user is selecting something and not on other primary events that might set off the secondary select event (focus, keypress, etc).这样,只有在用户选择某些东西时才会执行逻辑,而不是在可能引发次要 select 事件(焦点、按键等)的其他主要事件上执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.