首页 > 解决方案 > 如何更改 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,
};

标签: javascriptreactjs

解决方案


推荐阅读