gpt4 book ai didi

javascript - 使用 react-select 及其 menuIsOpen 属性的问题

转载 作者:行者123 更新时间:2023-11-30 06:18:40 25 4
gpt4 key购买 nike

我正在处理一个需要使用选项列表的复杂组件。我已经在我的应用程序中使用了 react-select,因此在这种情况下重用它是有意义的。我正在尝试嵌入 react-select 与公开的选择列表内联但隐藏 Controller /输入/指示器。基本上,我只想要列表。我可以让它工作,并且用鼠标一切正常,但当我关注与选择选项有关的焦点问题时,我遇到了问题。

是否有正确的方法来初始化菜单列表/第一个选项的焦点?

这是我正在尝试做的事情的一个基本示例...我想在组件完成安装时设置焦点。

在 mount 上,我尝试了很多东西。将焦点设置到选择中的 refs。使用查询选择器来关注选项本身......我也不得不尝试自定义组件,但似乎某些组件仍然需要处于事件状态才能使焦点状态正常工作。例如,值(value)容器。如果我将它们作为 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 并有建议?是否需要设置或触发某些内容才能使焦点在选项上正常工作?我假设当用户触发 select 扩展时,react select 会在幕后做一些事情,而在这种情况下没有设置这些。

最佳答案

为了满足您的所有要求,我会尝试如下解决方案:

  1. 使用menuIsOpen 属性来管理菜单选项的状态
  2. 使用自定义组件移除控制元素
  3. 设置一个 defaultValue 以聚焦所需的选项

这里是代码:

const options = [
{
label: "1",
value: 1
},
{
label: "2",
value: 2
},
,
{
label: "3",
value: 3
},
{
label: "4",
value: 4
}
];

const Control = props => (
<components.Menu {...props}>{props.children}</components.Menu>
);

function App() {
return (
<div className="App">
<Select
defaultValue={{ label: "1", value: 1 }}
components={{ Control }}
menuIsOpen={true}
options={options}
/>
</div>
);
}

提供现场示例 here .

关于javascript - 使用 react-select 及其 menuIsOpen 属性的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54679345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com