[英]How to use menuIsOpen prop of Select component from react-select dependency to display a button conditionally?
[英]Issues using react-select and it's menuIsOpen property
我正在研究一個要求使用選項列表的復雜組件。 我已經在整個應用程序中使用了react-select,因此在這種情況下可以重用它。 我試圖在嵌入選擇列表的情況下嵌入react-select內聯,但隱藏控制器/輸入/指示器。 基本上,我只想要列表。 我可以使它正常工作,並且用鼠標既好又花哨,但是當我關注有關選擇選項的問題時,我遇到了問題。
有沒有正確的方法來初始化焦點在菜單列表/第一個選項上?
這是我要執行的操作的基本示例...當組件完成安裝后,我想設置焦點。
在坐騎上,我嘗試了很多事情。 將焦點設置為選擇中的參考。 使用查詢選擇器來專注於選項本身...我還不得不使用自定義組件,但是看來某些組件仍需要處於活動狀態,焦點狀態才能正常工作。 例如,值容器。 如果我將它們返回為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
這樣的方式並提出建議? 我是否需要設置或觸發某些內容才能使焦點正確運行在選項上? 我假設當用戶觸發選擇范圍擴展並且在此實例中未進行設置時,react select會在后台執行一些操作。
為了滿足您的所有要求,我將嘗試以下解決方案:
menuIsOpen
道具來管理菜單選項的狀態 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>
);
}
此處提供現場示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.