在输入中显示突出显示的文本

Show highlighted text in input

提问人:Yousuf Sheikh 提问时间:11/6/2023 最后编辑:Yousuf Sheikh 更新时间:11/16/2023 访问量:158

问:

我正在尝试做如下的事情,即我有一个带有建议下拉列表的输入,这个 Male 和 Female 中只有 2 个值 如果我键入 M,剩余的字母 ale 会在输入中突出显示,通过单击它或按 Tab 键,它会自动填充 反之亦然,女性 有没有图书馆?

我已经尝试了以下代码,但由于显而易见的原因,它没有显示任何突出显示的文本,并且在使用类型 M 或 F 时会自动填充,问题是由于以下情况,它不允许我擦除值

我正在附上一张图片供参考,这是gmail搜索中的一个功能 gmail搜索功能

if (name === 'patient_gender') {
        if (input.toLowerCase().startsWith('m')) {
            input = 'Male';
        } else if (input.toLowerCase().startsWith('f')) {
            input = 'Female';
        }
    }
ReactJS TypeScript 下拉列表 突出显示 搜索建议

评论

0赞 i2i3 11/6/2023
请提供UI的视图部分。我的一部分猜测你需要使用.useState

答:

0赞 ramoneguru 11/7/2023 #1

这有点棘手,看起来谷歌使用了 2 个输入框,做了一些 z 索引开关,然后做了一些其他事情,比如捕获右箭头/制表符以自动完成等等。

我有一个非常粗略的演示,代码发布在这里供后人使用。你必须填补缺失的部分,但希望这能给你一个开始。

沙盒链接

import React from "react";
import "./styles.css";

export default function App() {
  const [userInput, setUserInput] = React.useState<string>("");
  const [autoInput, setAutoInput] = React.useState<string>("");
  const [userInputStyle, setUserInputStyle] = React.useState({ left: "0" });
  const [autoInputStyle, setAutoInputStyle] = React.useState();
  const MALE = "ale";
  const handleInputChange = (e) => {
    const str = e.target.value;
    if (str === "m") {
      // hardcoded width for demo, but useRef would  be better to get a more exact width
      const autoInputStyleChange = { right: 0, width: "458px" };
      const userInputStyleChange = { zIndex: "1" };
      setAutoInput(MALE);
      setUserInputStyle(userInputStyleChange);
      setAutoInputStyle(autoInputStyleChange);
    }
    setUserInput(str);
  };

  return (
    <div className="App">
      <h1>Test Input</h1>
      <form>
        <section className="input-wrapper">
          <input
            style={userInputStyle}
            className="user-input"
            type="text"
            value={userInput}
            onChange={handleInputChange}
          />
          <input
            style={autoInputStyle}
            className="auto-input"
            type="text"
            placeholder={autoInput}
          />
        </section>
      </form>
    </div>
  );
}

基本 CSS

.input-wrapper {
  position: relative;
  width: 100%;
}

.user-input,
.auto-input {
  position: absolute;
  top: 0;
  z-index: 5;
  border: 0;
  width: 100%;
}

.user-input {
  z-index: 6;
  left: 0;
  border: 1px solid blue;
  color: blue;
}

.auto-input {
  top: 1px;
  border: 0;
  outline: none;
  padding: 1px 0;
}