如果输入在ReactJS中已经有焦点,则阻止设置焦点onClick


ReactJS/MaterialUI新手问题。我有一个由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 }];

使用mousedown事件代替

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

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

最新更新