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

标签 reactjs react-select

当我在下拉列表中选择一个已选择的值时,将触发 react-select 下拉列表的 onChange。如果再次选择已选择的值,是否可以将 react-select 配置为不触发 onChange 事件。

这是一个 codesandbox关联。尝试选择紫色,您可以在控制台中看到日志。下面是相同的代码,以防您想立即看到它。

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组件转换为受控组件并 checkin 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}
        />
    );
}

关于reactjs - 如果在 react-select 中选择了相同的选项,则不要触发 onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55624804/

相关文章:

reactjs - 如何将 react DnD 与 react 全日历集成?

javascript - React js,为什么当我更改 open 的值时我的组件没有重新渲染?

reactjs - React + Redux - 在初始加载时触发选择 onChange()

reactjs - react 数据网格自动完成编辑器不工作

reactjs - 使用 Express 服务 REACT 组件不起作用(仅呈现 html 文件)

javascript - react : avoid child component rerender on state change

rest - 如何将 React-Select 与 Rest API(远程数据)集成

reactjs - 如何更改 react-select 所选选项的样式?

reactjs - 如何添加添加键到 react 选择多重?