首页 > 解决方案 > react-select : 选项 `isSelected` 始终为真

问题描述

当没有选择任何内容时

当没有选择任何内容时

当没有选择任何内容时,它工作得很好。

选择一个选项时(问题)

选择时

正如您在上面看到的,即使我选择了一个选项(ash),它也表示所有内容都已选择。我做了console.log(isSelected),它说一切都被选中了true..

应该是这样的……

反应选择选定的道具

我复制了很多代码,修改了几行。

这是我的代码

预先感谢您帮助我!

如果你有什么建议,请打我!

const dot = (color = '#ccc') => ({
  display: 'flex',
  alignItems: 'center',

  ':before': {
    backgroundColor: color,
    borderRadius: 10,
    content: '" "',
    display: 'block',
    marginRight: 10,
    height: 15,
    width: 15,
  },
});

const colourStyles = {
  control: (styles, { selectProps: { width } }) => ({
    ...styles,
    width: width,
  }),
  option: (styles, { data, isSelected, isFocused }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: isSelected
        ? data.color
        : isFocused
        ? color.alpha(0.1).css()
        : null,
      color: isSelected
        ? chroma.contrast(color, 'white') > 2
          ? 'white'
          : 'black'
        : data.color,
    };
  },
  input: (styles) => ({ ...styles, ...dot() }),
  placeholder: (styles) => ({ ...styles, ...dot() }),
  singleValue: (styles, { data }) => ({ ...styles, ...dot(data.color) }),
};


const SelectModule = observer(({ label, value }) => {
  const [selectedOption, setSelectedOption] = useState('');

  const options = colorChipListStore.colorList.map((item) => ({
    color: item.hexId,
    label: item.label,
  }));


  const setColors = (color) => {
    setSelectedOption(color);
  };

  function customTheme(theme) {
    return {
      ...theme,
      colors: {
        ...theme.colors,
        primary: '#AD9EE5',
      },
    };
  }


return (
    <Container>
      {label && <Label>{label}</Label>}
      <OptionWrapper>
          <Select
            width='100%'
            options={options}
            styles={colourStyles}
            theme={customTheme}
            isSearchable
            onChange={setColors}
            defaultValue={selectedOption}
          />
      </OptionWrapper>
    </Container>
  );
});

标签: reactjsreact-select

解决方案


您的选项对象没有值键。我也得到了这个,但是当我将选项更改为格式时: options = [{label: '', value: ''}] 我能够选择正确的选项。默认行为是使用 'value' 键进行选定选项检查。您可以通过使用“isOptionSelected”并将选项重置为您希望用作检查的任何键来更改此行为。您还可以向对象添加值。

请参阅此GitHub 问题


推荐阅读