【发布时间】:2019-02-15 06:28:21
【问题描述】:
我正在处理一个需要使用选项列表的复杂组件。我已经在整个应用程序中使用 react-select,因此在这种情况下重用它是有意义的。我正在尝试将 react-select 嵌入到暴露的选择列表中,但隐藏控制器/输入/指示器。基本上,我只想要清单。我可以让它工作,用鼠标一切都很好,而且花花公子,但是当我关注有关选择选项的问题时,我遇到了问题。
是否有正确的方法来初始化菜单列表/第一个选项的焦点?
这是我正在尝试做的一个基本示例...我想在组件完成安装后设置焦点。
在安装时,我尝试了很多东西。将焦点设置为选择中的 refs。使用查询选择器来关注选项本身......我还不得不使用自定义组件,但似乎某些组件仍然需要处于活动状态才能使焦点状态正常工作。例如,值容器。如果我将它们作为 null 返回,则组件在焦点方面无法正常运行。
// tried setting focus on the option directly
const option: any = this.selectRef.menuListRef.querySelector(
'.va-select__option'
);
option.click(); // does work
option.focus(); // appears to do nothing, but I believe react select manages this all behind the scenes
// tried setting focus on the input or triggering a click
this.selectRef.inputRef.focus();
this.selectRef.inputRef.click();
// Attempted using all of these refs and setting focus:
controlRef
inputRef
menuListRef
示例组件:
interface DropdownProps {
isLoading?: boolean;
}
function EmptyComponent(): React.ReactElement<any> {
return <></>;
}
export class Dropdown extends React.Component<DropdownProps> {
selectRef: any;
componentDidMount(): void {
this.selectRef.menuListRef.focus();
}
setSelectRef = (element: any): void => {
if (element) {
this.selectRef = element.select.select;
}
};
render(): React.ReactNode {
const { isLoading } = this.props;
const customComponents: SelectComponentsConfig<any> = {
IndicatorsContainer: EmptyComponent,
Input: EmptyComponent,
Placeholder: EmptyComponent
};
return (
<div>
<Select
components={customComponents}
isLoading={isLoading}
menuIsOpen={true}
options={[
{
label: 'Group 1',
value: 'Value 1'
},
{
label: 'Group 2',
value: 'Value 2'
},
{
label: 'Group 3',
value: 'Value 3'
},
{
label: 'Group 4',
value: 'Value 4'
}
]}
reference={this.setSelectRef}
/>
{isLoading && <div>Loading</div>}
</div>
);
}
}
我似乎无法让焦点状态正常工作,我觉得我有点把它搞砸了。
过去有没有人以这种方式使用过react-select 并提出建议?是否需要设置或触发某些内容才能使焦点在选项上正常工作?我假设当用户触发选择展开并且在此实例中没有设置时,反应选择在幕后做了一些事情。
【问题讨论】:
-
您好,总结一下您的目标,您希望在挂载组件时打开菜单选项?
-
是的,基本上在安装组件时应该已经暴露了选择菜单。我也在努力隐藏控制器组件。
-
我确实发现这样做是可行的,但必须有更好的方法来正确设置焦点和正确初始化键盘事件。
componentDidMount(): void { setTimeout(() => { const clickEvent: MouseEvent = document.createEvent('MouseEvents'); clickEvent.initEvent('mousedown', true, true); this.selectRef.controlRef.dispatchEvent(clickEvent); }, 0); } -
关于打开菜单选项我建议你看看这个另一个问题stackoverflow.com/questions/54266127/…
-
是的,这涵盖了基础知识,但是如何将焦点设置在选择中的第一个选项上?
标签: javascript reactjs react-select