document.selection.createRange(),React流程中的错误

时间:2018-02-20 05:21:38

标签: javascript reactjs flowtype

我试图在mouseup事件的反应页面上获取用户选择的文本。

selText = document.selection.createRange().text;
<{1>} npm run check我收到了错误:selText = document.selection.createRange().text; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call of method createRange . Method cannot be called on

如何修复此错误。如果忽略Flow错误,这段代码就可以了。

1 个答案:

答案 0 :(得分:0)

document.selection的类型定义被定义为可能为空的值。 Flow告诉你,你需要在调用selection之前检查对象createRange()是否存在,否则你可能会遇到运行时错误。

例如,您可以使用if语句来保护代码免受可能的运行时错误的影响并解决类型错误。

let selText;

if (document.selection) {
  selText = document.selection.createRange().text;
}