如何将“inputRef”传递给Material UI 的 useAutocomplete?
我需要在输入上分配一个自定义引用,但是 useAutocomplete 中的
getInputProps()
已经设置了所需的引用。
我尝试了几件事,比如添加引用。然后我的其他代码将起作用,但 useAutocomplete 将无法起作用,因为它依赖于在输入上设置的它自己的“ref”属性。
关于 useAutocomplete 或可提供的选项也没有太多文档,因此很难调试。
我们可以通过
getInputProps().ref
获取inpuRef的ref。
例如,要使用热键(“control+q”焦点并选择输入值),
我使用下面的代码。 (我希望下面对任何使用 useAutocomplete 的人有所帮助)
import {useHotkeys} from 'react-hotkeys-hook';
...
const {
getRootProps,
getInputLabelProps,
getInputProps,
getListboxProps,
getOptionProps,
groupedOptions,
value
} = useAutocomplete({
id: 'use-autocomplete-demo',
options: options,
limit: 10,
freeSolo: true,
autoSelect: false,
clearOnBlur: true,
selectOnFocus: true,
filterOptions: options => options,
getOptionLabel: (option) => {
if(typeof(option) === 'object'){
return `${option.artistName} ${option.songName}`
}
return option;
}
});
const inputRef = getInputProps().ref;
useHotkeys('ctrl+q',() => {
inputRef.current.focus()
inputRef.current.select()
}, [inputRef.current]);
...
...
...
return (
<div>
<div {...getRootProps()}>
<Input
onKeyDownCapture={handleKeyDown}
onKeyPressCapture={handleKeyPressed}
onFocus={handleFocus}
placeholder="control + q"
{...getInputProps()}
/>
</div>
....
目前,React 无法合并两个引用(来自参数的引用和钩子的引用),但仍然有几种方法可以实现这一点。
使用 react-merge-refs,我们可以实现类似于下面的东西:
import React from "react";
import { mergeRefs } from "react-merge-refs";
const Example = React.forwardRef(function Example(props, ref) {
const localRef = React.useRef();
return <div ref={mergeRefs([localRef, ref])} />;
});
正如库作者所写,这有利于使 UI 库组件更加灵活。
如果您无法使用库,那么您唯一的选择就是操作 DOM 元素。 对于上面的代码,由于输入引用被用作该钩子的依赖项,因此更难以实现相同的性能优势,但对于简单的情况,您可以使用 querySelector() 实现纯 js,如下所示:
const handleKeyEvent = () => {
const inputElement = document.querySelector('#focus-input');
if (inputElement) {
inputElement.focus();
}
}
useHotkeys('ctrl+q', handleKeyEvent, []);
不建议使用空依赖数组,因此仅在绝对绝望的情况下使用选项 2