javascript - 如何更改 React Dropdown 的标题?
问题描述
我正在创建一个自定义下拉列表,其中一个按钮 ( Trigger
) 充当下拉列表的触发器。在这里,我试图将下拉标题更改为任何选定选项的名称。为此,我将新选择的值存储在selectedOption
其中并使用它们来替换标题。但是收到以下错误:Cannot read property 'label' of undefined
。
如何解决并使下拉菜单起作用?
真的很感激任何启示!谢谢
const Dropdown = props => {
const { onChange, label, disabled } = props;
const options = [
{ value: '0', label: 'All Flavour' },
{ value: '1', label: 'Strawberry' },
{ value: '2', label: 'Rum Raisin' },
{ value: '3', label: 'Hazelnut' },
{ value: '4', label: 'Chocochip' },
{ value: '5', label: 'Coffee' },
];
const [open, setOpen] = useState(false);
const handleTriggerClick = useCallback(() => setOpen(prev => !prev), []);
const handleChange = useCallback(
newValue => {
if (!disabled) {
onChange(newValue);
setOpen(false);
}
},
[onChange]
);
const selectedOption = options.find(option => option.label === label);
const displayMenu = open && !disabled;
return (
<>
<Container>
<OutletIcon />
<Trigger
disabled={disabled}
title={selectedOption.label || ''}
onClick={handleTriggerClick}
>
<TriggerText>{selectedOption.label || ''}</TriggerText>
<SortIcon />
</Trigger>
<DropdownMenu isDisplayed={displayMenu}>
{options.map(option => {
const isSelected = option.label === label;
const otherProps = {};
if (!isSelected) {
otherProps.onClick = () => handleChange(option.label);
}
return (
<DropdownMenuItem
key={option.value}
title={option.label}
selected={isSelected}
{...otherProps}
>
<DropdownMenuItemText onClick={handleTriggerClick}>
{option.label}
</DropdownMenuItemText>
<GreenCheckIcon />
</DropdownMenuItem>
);
})}
</DropdownMenu>
</Container>
</>
);
};
特此声明道具
Dropdown.defaultProps = {
disabled: false,
onChange: () => {},
label: '',
};
Dropdown.propTypes = {
disabled: PropTypes.bool,
onChange: PropTypes.func,
label: PropTypes.string,
};
解决方案
推荐阅读
- python - 我正在抓取具有相似词典的链接。如何区分每个字典?
- json - 基于名称提取 id 的 JSON 查询
- python - 如何使用 Google OR 工具在 VRPTW 中添加分离、设置惩罚和防止某些位置被丢弃?
- html - CSS Grid:同一页面中不同网格容器的相同内容名称和区域名称
- javascript - discord.js 参数 startsWith 不能是正则表达式
- regex - 仅在下一次关闭时移除左括号
- html - 如何交换两个 HTML 的选项值
- vue.js - 每当页面更改时显示微调器(预加载器/加载指示器)并在 Vue Gridsome 中加载所有资产时隐藏
- python - python中的和+有什么区别
- .net-core - 使用 Blazor 访问设备摄像头