【问题标题】:Property 'selectionStart' does not exist on type 'EventTarget'“EventTarget”类型上不存在属性“selectionStart”
【发布时间】:2021-03-19 14:27:50
【问题描述】:

我使用selectionStart 和selectionEnd 来获取文本选择的起点和终点。

代码:https://codesandbox.io/s/busy-gareth-mr04o

但是,我正在努力定义可以调用它们的事件类型。 如果我使用any,代码可以正常工作,但我希望知道正确的事件。

我尝试了以下类型: Element React.SyntheticEvent<HTMLDivElement> <HTMLDivElement> 没有运气

export default function App() {
  const [startText, setStartText] = useState<number | undefined>();
  const [endText, setEndText] = useState<number | undefined>();

  const handleOnSelect = (event: any) => { <--- I CANNOT FIND THE RIGHT EVENT TYPE
    setStartText(event.target.selectionStart);
    setEndText(event.target.selectionEnd);
  };

  return (
    <Grid container direction="column" className="App">
      You can type here below:
      <TextField
        value={"This is a example, select a word from this string"}
        onSelect={(event) => handleOnSelect(event)}
      />
      <br />
      <Grid item>The selected word starts at character: {startText}</Grid>
      <Grid item>The selected word ends at character: {endText}</Grid>
    </Grid>
  );
}

【问题讨论】:

    标签: javascript reactjs typescript material-ui


    【解决方案1】:

    这是一个棘手的问题,因为 material-ui TextField 组件涉及多个嵌套节点。传递给onSelect 函数的参数是div。然而,事件本身发生在 div 内的 input 上。

    const handleOnSelect = (event: React.SyntheticEvent<HTMLDivElement, Event>) => {
        console.log(event.target, event.currentTarget);
    };
    

    这会记录input,然后是div。

    使用event.currentTarget 可以获得非常具体的Typescript 信息。我们知道这是一个HTMLDivElement。但是div 没有我们想要访问的属性selectionStart 和selectionEnd。这些存在于input。

    event.target 为我们提供了一个非常模糊的 EventTarget 类型。我们不知道目标是input。

    一种选择是在运行时验证元素。

    const handleOnSelect = (event: React.SyntheticEvent<HTMLDivElement, Event>) => {
        if ( event.target instanceof HTMLInputElement ) {
            setStartText(event.target.selectionStart);
            setEndText(event.target.selectionEnd);
        }
    };
    

    既然您知道该事件将始终在HTMLInputElement 上发生,我认为做出断言是安全的。

    const handleOnSelect = (event: React.SyntheticEvent<HTMLDivElement, Event>) => {
        const target = event.target as HTMLInputElement;
        setStartText(target.selectionStart);
        setEndText(target.selectionEnd);
    };
    

    注意selectionStart 和selectionEnd 属性使用null 而不是undefined。因此,您需要将状态类型更改为 &lt;number | null&gt; 或使用空合并 event.target.selectionStart ?? undefined 将 null 替换为 undefined。

    【讨论】:

    • 非常感谢!我选择退出 const target = event.target as HTMLInputElement,因为 if 子句总是被跳过 (event.target instanceof HTMLInputElement)
    猜你喜欢
    • 2021-02-08
    • 2019-01-28
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-18
    • 2018-04-30
    • 2021-06-03
    相关资源
    最近更新 更多