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

use*_*655 2 reactjs react-select

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

我正在使用具有多选功能的 react-select ( https://react-select.com/home )。很有魅力,但我想让值可点击/可切换以更改颜色/状态(而不是添加/删除)。最后以灰色/颜色显示它们以指示标记状态并将底层状态用于后续代码。有什么方法可以实现这一目标,如果有,如何实现?

Lee*_*Lee 5

您可以传入自定义MultiValueLabel或MultiValueContainer添加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);
Run Code Online (Sandbox Code Playgroud)

工作示例

  • 非常感谢!这几乎完美无缺。此外,我禁用了在单击值时打开菜单 + 确保在切换值时选择模糊:https://codesandbox.io/s/staging-frog-9gbex (2认同)