我正在使用 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>
);
}
最佳答案
这是一个棘手的问题,因为 material-ui TextField
组件涉及多个嵌套节点。传递给 onSelect
的参数函数是 div
.然而,事件本身发生在 input
里面div
.
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
.因此,您需要将状态类型更改为 <number | null>
或替换 null
与 undefined
通过使用空值合并 event.target.selectionStart ?? undefined
.
关于javascript - 类型 'selectionStart' 上不存在属性 'EventTarget',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66710037/