React-Select - 带有自定义处理程序的可点击值

React-Select - clickable values with custom handler

使用 react-select,我想了解如何获取单击 selected 值(多个)时的事件。

我正在使用具有多重 select 功能的 react-select (https://react-select.com/home)。 很有魅力,但我想让值 clickable/toggleable 更改 color/state(而不是 add/remove)。最后在 grey/color 中显示它们以指示标记状态并将基础状态用于后续代码。 有什么办法可以做到这一点,如果可以的话,怎么做?

您可以传入自定义 MultiValueLabelMultiValueContainer 并添加 onClick 处理程序。

import React from "react";
import ReactDOM from "react-dom";
import Select, { components } from 'react-select';


const options = [
  {value: '1', label: 'Item 1', isToggled: true},
  {value: '2', label: 'Item 2', isToggled: false},
  {value: '3', label: 'Item 3', isToggled: false},
  {value: '4', label: 'Item 4', isToggled: false},
  {value: '5', label: 'Item 5', isToggled: false},
  {value: '6', label: 'Item 6', isToggled: false},
]

const ReactSelectStyles = () => ({
  multiValueLabel: (styles, {data: { isToggled }}) => ({
    ...styles,
    backgroundColor: isToggled ? 'hotpink' : null,
    color: isToggled ? 'white' : null
  }),
});

const handleMultiValueClick = (e, props) => {
  e.stopPropagation();
  e.preventDefault();


  console.log('A multi value has been clicked', props);

  const option = options.find(option => option.value === props.data.value);

  option.isToggled = !option.isToggled
}

const MultiValueLabel = props => {
  return (
    <div onClick={(e) => handleMultiValueClick(e, props)}>
      <components.MultiValueLabel {...props} />
    </div>
  );
};

function App() {
  return (
    <Select
    closeMenuOnSelect={false}
    components={{ MultiValueLabel }}
    defaultValue={[options[0], options[2], options[4]]}
    isMulti
    options={options}
    styles={ReactSelectStyles()}
  />
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Working Example