判断所选内容的type
是否为"范围".如果是,请不要更新状态:
document.getSelection().type === 'Range'
工作示例:
const { useState } = React;
const Demo = () => {
const [edit, setEdit] = useState(false);
function editTodo(index) {
if (document.getSelection().type === 'Range') return;
setEdit(true)
}
return (
<div>
<h2
onClick={() => editTodo()}
onSelectStart={e => stopPropogation()}
>text</h2>
<div>Edit: {JSON.stringify(edit)}</div>
</div>
)
}
ReactDOM
.createRoot(root)
.render(<Demo />)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
此外,您的editTodo
函数有点麻烦,您可以让它更简洁一些(请参见代码中的注释):
function editTodo(index) {
if(document.getSelection().type === 'Range') return; // bail out
setList(prevList => // use an updater functio get the previous state
prevList.map((x, i) => // use an arrow function to avoid the need for explicit return
i !== index // use a ternary instead of if/else
? x
: { ...x, edit: true }
)
)
}