如果在 react-select 中 selected 相同的选项,则不要触发 onChange

Don't trigger onChange if same option is selected in react-select

onChange 当我 select 下拉列表中已经 selected 值时,会触发 react-select 下拉菜单吃下。如果已经 selected 值再次被 selected,有没有办法配置 react-select 不触发 onChange 事件。

这里有一个codesandboxlink。尝试 selecting Purple,您可以在控制台中看到日志。如果您想立即查看,下面是相同的代码。

import chroma from 'chroma-js';

import { colourOptions } from './docs/data';
import Select from 'react-select';

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

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

const colourStyles = {
  control: styles => ({ ...styles, backgroundColor: 'white' }),
  option: (styles, { data, isDisabled, isFocused, isSelected }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: isDisabled
        ? null
        : isSelected ? data.color : isFocused ? color.alpha(0.1).css() : null,
      color: isDisabled
        ? '#ccc'
        : isSelected
          ? chroma.contrast(color, 'white') > 2 ? 'white' : 'black'
          : data.color,
      cursor: isDisabled ? 'not-allowed' : 'default',
    };
  },
  input: styles => ({ ...styles, ...dot() }),
  placeholder: styles => ({ ...styles, ...dot() }),
  singleValue: (styles, { data }) => ({ ...styles, ...dot(data.color) }),
};

const logConsole = (selectedVal) => {
  console.log(selectedVal)
}

export default () => (
  <Select
    defaultValue={colourOptions[2]}
    label="Single select"
    options={colourOptions}
    styles={colourStyles}
    onChange={logConsole}
  />
);

一个可能的解决方案是使用 hideSelectedOptions 属性隐藏所选值。

<Select
    { ... }
    hideSelectedOptions
/>

另一种解决方案是将您的 Select 组件更改为受控组件并检查 onChange 处理程序,如果所选值与当前所选值匹配,则什么也不做。

class MySelect extends Component {
    state = {
       value: null
    }

    onChange = (selectedValue) => {
        const { value } = this.state;
        if (value && value.value === selectedValue.value) return;

        // Do whatever you want here

        this.setState({ value: selectedValue });
    }

    render = () => (
        <Select
            { ... }
            value={this.state.value}
            onChange={this.onChange}
        />
    );
}