【问题标题】:Prevent set focus onClick if the input already has focus in ReactJS如果输入已经在 ReactJS 中具有焦点,则防止设置焦点 onClick
【发布时间】:2021-09-13 12:23:10
【问题描述】:

ReactJS/Material-UI 新手问题。我有一个由 useEffect 和钩子组成的功能组件。为简单起见,我创建了下面的代码示例。如果您单击自动完成容器边界内的任意位置(由红色边框表示),它会将焦点设置在输入字段上。但是,如果您再次单击边界,您会注意到它会再次设置焦点。如果没有使用 document.activeElement 并避免使用反模式,我试图只在输入字段的焦点尚未设置的情况下将焦点设置在输入字段上。我目前正在使用 useRef,但不确定是否需要使用 useEffect、useState,或者我是否可以通过检查选项列表是否可见来以某种方式利用自动完成组件。非常感谢任何帮助。沙盒链接https://codesandbox.io/s/solitary-fog-2t7p4?file=/src/demo.js

代码示例

import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  const container = React.useRef();
  const input = React.useRef();

  return (
    <>
      <div
        ref={container}
        style={{ padding: 30, border: "1px solid red" }}
        onClick={() => {
          if (!input.current.focused) {
            input.current.focus();
          }
        }}
      >
        <Autocomplete
          options={top100Films}
          getOptionLabel={(option) => option.title}
          openOnFocus
          selectOnFocus
          style={{ width: 300 }}
          renderInput={(params) => (
            <TextField
              inputRef={input}
              {...params}
              label="Combo box"
              variant="outlined"
            />
          )}
        />
      </div>
    </>
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 },
  { title: "The Dark Knight", year: 2008 },
  { title: "12 Angry Men", year: 1957 }];

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    改用mousedown 事件

    onMouseDown={(event) => {
      event.preventDefault();
      input.current.focus();
    }}
    

    不确定如何在移动设备上处理此问题,请尝试touchstart 事件。

    【讨论】:

    • 非常感谢!那成功了。简单的解决方案。我想太多了,因为我不确定它是否需要 useState 或 useEffect。我还没有决定是否将这个功能保留在移动设备上,所以现在不关心它是否在移动设备上工作。再次感谢!
    猜你喜欢
    • 2011-10-05
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    相关资源
    最近更新 更多