类型“EventTarget”上不存在属性“selectionStart”

FBS*_*BSO 8 javascript typescript reactjs material-ui selection-api

我正在使用selectionStartandselectionEnd来获取文本选择的起点和终点。

代码: 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

Lin*_*ste 13

这是一个棘手的问题,因为 Material-uiTextField组件涉及多个嵌套节点。传递给函数的参数onSelect是 a div。然而,事件本身发生inputdiv.

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

这会记录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);
    }
};
Run Code Online (Sandbox Code Playgroud)

由于您知道该事件将始终发生在 a 上HTMLInputElement,因此我认为做出断言是安全的。

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

请注意,selectionStartselectionEnd属性使用null而不是undefined。因此,您需要将状态类型更改为<number | null>或使用 null coalescingnull替换。undefinedevent.target.selectionStart ?? undefined