【问题标题】:React: How to set the cursor selectionReact:如何设置光标选择
【发布时间】:2023-02-13 21:48:22
【问题描述】:

我正在使用自定义库,我需要在其中手动设置光标选择。这是我输入的代码:

import React, { useState } from 'react';
import { useDrag } from 'react-dnd'
import { Validation } from "../types";
...
  <input
    ref={forwardRef}
    id={id}
    type={type}
    placeholder={placeholder}
    value={value}
    onChange={onChange}
    onKeyDown={onKeyDown}
    onBlur={onBlur}
    name={name}
    disabled={disabled}
    className={`fb-form-control goggo ${validation?.type}`}
    checked={!!checked}
    draggable={true}
    onDragStart={(event) => event.preventDefault()}
    onMouseEnter={()=>console.error("onMouseEnter", "onMouseEnter")}
    onMouseLeave={() => console.error("onMouseLeave", "onMouseLeave")}
    onDoubleClick={() => console.error("I have been double clicked!")}
  />

我需要将 () =&gt; console.error("I have been double clicked!") 替换为对将选择输入文本的函数的调用。此代码:onDoubleClick={() =&gt; console.error("this", document.getElementById(String(id))?.select())} 导致“TS2551: Property 'select' does not exist on type 'HTMLElement'. Did you mean 'onselect'?

【问题讨论】:

  • 你试过onDoubleClick={() =&gt; (document.getElementById(String(id)) as HTMLInputElement)?.select()}了吗?

标签: reactjs


【解决方案1】:

你可以使用window.getSelection来选择输入的文本:

onDoubleClick={() => {
  const input = document.getElementById(String(id)) as HTMLInputElement;
  const selection = window.getSelection();
  const range = document.createRange();
  range.selectNodeContents(input);
  selection.removeAllRanges();
  selection.addRange(range);
}}

【讨论】:

  • 我试过了,我得到了:TS18047:“选择”可能是“空”。
【解决方案2】:

使用事件目标而不是 getElementById:

onDoubleClick={(event) => event.target.select()}

【讨论】:

  • 我试过了。我得到:TS2339:属性“select”在类型“EventTarget”上不存在。
猜你喜欢
  • 2021-11-19
  • 1970-01-01
  • 2016-02-14
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
  • 2018-08-16
相关资源
最近更新 更多