【问题标题】:How can I do to select all in a multi select using React.js?如何使用 React.js 在多选中全选?
【发布时间】:2021-03-06 15:49:11
【问题描述】:

https://codesandbox.io/s/codesandboxer-example-forked-wkpht

import React from 'react';
import chroma from 'chroma-js';

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

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',

      ':active': {
        ...styles[':active'],
        backgroundColor: !isDisabled && (isSelected ? data.color : color.alpha(0.3).css()),
      },
    };
  },
  multiValue: (styles, { data }) => {
    const color = chroma(data.color);
    return {
      ...styles,
      backgroundColor: color.alpha(0.1).css(),
    };
  },
  multiValueLabel: (styles, { data }) => ({
    ...styles,
    color: data.color,
  }),
  multiValueRemove: (styles, { data }) => ({
    ...styles,
    color: data.color,
    ':hover': {
      backgroundColor: data.color,
      color: 'white',
    },
  }),
};

export default () => (
  <Select
    closeMenuOnSelect={false}
    defaultValue={[colourOptions[0], colourOptions[1]]}
    isMulti
    options={colourOptions}
    styles={colourStyles}
  />
);

我有这段代码使用 React.js,我想添加“全部”,当我选择所有项目时,选择中的所有项目都被选中。 我该怎么做?

【问题讨论】:

    标签: javascript reactjs select multi-select


    【解决方案1】:

    您需要添加一个选项来选择所有值并将所选选项存储在状态中。选择“全部”选项时,单击未选择时,将状态和未设置的所有选项设置。

    注意:“全选”选项和“取消全选”选项必须具有相同的值才能执行切换操作。

    我已经更新了执行这些操作的代码。 参考:https://codesandbox.io/s/codesandboxer-example-forked-3j7lf?file=/example.js

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 2018-01-31
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2019-11-03
      • 2011-09-06
      相关资源
      最近更新 更多