如何使反应选择选项菜单从选项数组的特定索引开始

问题描述 投票:0回答:1

在反应选择中,我有一个很长的选项列表,如下所示,很难选择最后一个选项之一
用户必须向下滚动所有选项才能获得最后一个选项

有没有办法从数组列表的中间启动选择菜单的选项?

就像从选项[20]开始,用户可以向下和向上滚动以获取第一个或最后一个选项

我有一系列这样的选项:

const options = [
 {
        label : '04:45',
        value : '04:45'
    },
    {
        label : '05:00',
        value : '05:00'
    },
    {
        label : '05:15',
        value : '05:15'
    },
    {
        label : '05:30',
        value : '05:30'
    },
    {
        label : '05:45',
        value : '05:45'
    },
    {
        label : '06:00',
        value : '06:00'
    },
    {
        label : '06:15',
        value : '06:15'
    },
    {
        label : '06:30',
        value : '06:30'
    },
    {
        label : '06:45',
        value : '06:45'
    },
    {
        label : '07:00',
        value : '07:00'
    },
    {
        label : '07:15',
        value : '07:15'
    },
]

并使用反应选择

<Select 
isRtl
options={hours}
unstyled
isSearchable={false}
/>

我尝试了defaultValue,但它的行为并不像我期望的那样

reactjs react-select
1个回答
0
投票

使用 自定义选项组件,选择选项时调用

scrollIntoView({ behavior: "instant", block: "center" })

const hours = [
    {
        label: '04:45',
        value: '04:45'
    },
    {
        label: '05:00',
        value: '05:00'
    },
    {
        label: '05:15',
        value: '05:15'
    },
    {
        label: '05:30',
        value: '05:30'
    },
    {
        label: '05:45',
        value: '05:45'
    },
    {
        label: '06:00',
        value: '06:00'
    },
    {
        label: '06:15',
        value: '06:15'
    },
    {
        label: '06:30',
        value: '06:30'
    },
    {
        label: '06:45',
        value: '06:45'
    },
    {
        label: '07:00',
        value: '07:00'
    },
    {
        label: '07:15',
        value: '07:15'
    },
    {
        label: '07:30',
        value: '07:30'
    },
    {
        label: '07:45',
        value: '07:45'
    }
];
const Option = (props) => {
    const ref = useRef();

    useEffect(() => {
        props.isSelected && ref.current.scrollIntoView({ behavior: "instant", block: "center" });
    }, [props.isSelected]);

    return (
        <components.Option {...props} innerRef={ref} />
    );
};

export default function () {
    const components = {
        Option: Option,
    }
    return (
        <Select
            components={components}
            // onMenuOpen={handleMenuOpen}
            isRtl
            defaultValue={hours[Math.floor(hours.length/2)]}
            options={hours}
            isSearchable={false}
        />
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.