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

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

当我在下拉列表中选择已选择的值时,会触发react-select下拉列表的onChange。有没有办法配置react-select以便在再次选择已选择的值时不触发onChange事件。

这是一个codesandbox链接。尝试选择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}
  />
);
reactjs react-select
1个回答
1
投票

一种可能的解决方案是使用hideSelectedOptions prop隐藏所选值。

<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}
        />
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.