在React-Select中用自定义文本替换clearIndicator X

问题描述 投票:0回答:2

我需要删除 MultiSelect 上的选择组件中的 clearIndicator 默认 X 并将其替换为自定义文本。有没有一种方法可以在不失去删除所选选项的能力的情况下执行此操作(如 isClearable={false} 发生的情况)?

代码:

export const MultiSelect = () => {
  const [selected, setSelected] = useState([]);

  const options = [
    { value: '1', label: 'Label1' },
    { value: '2', label: 'Label2' },
    { value: '3', label: 'Label3' },
  ];

const customStyles = {
    control: (prevStyle, { isFocused }) => ({
      ...prevStyle,
      backgroundColor: 'rgba(248, 251, 251, 1)',
      boxShadow: 'none',
      borderColor: isFocused ? 'black' : 'grey',
      ':hover': {
        borderColor: isFocused ? 'black' : 'grey',
      },
    }),
    clearIndicator: (prevStyle) => ({
      ...prevStyle,
      color: 'rgba(0, 0, 0, 0.4)',
      ':hover': {
        color: 'rgba(0, 0, 0, 0.4)',
      },
    }),
  };

return (
    <ReactSelect
      ref={reactSelectRef}
      placeholder={placeholder}
      instanceId={`multiselect-${id}`}
      styles={customStyles}
      isOptionSelected={isMulti && isOptionSelected}
      options={getOptions()}
      value={getValue()}
      onChange={isMulti ? onChangeHandler : onChange}
      hideSelectedOptions={false}
      closeMenuOnSelect={!isMulti}
      formatGroupLabel={formatGroupLabel}
      isMulti={isMulti}
    />
  );

reactjs react-select
2个回答
4
投票

React Select 可以选择传入您自己的自定义组件 Docs

看起来像这样

 <Select
    //You can pass in any component as the ClearIndidcator and do whatever customizations you want
    components={{ ClearIndicator: () => <div>Clear</div> }}
    {...props}
 />

0
投票

我发现了一个更好的解决方案

import React from 'react';
import Select from 'react-select';

const CustomClearText = () => <>Clear</>;

const ClearIndicator = (props) => {
  const { children = <CustomClearText />, getStyles, innerProps } = props;
  return (
    <div {...innerProps} style={getStyles('clearIndicator', props)}>
      <div style={{ padding: '0px 5px' }}>{children}</div>
    </div>
  );
};

const selectionStyles = {
  clearIndicator: (base, state) => ({
    ...base,
    cursor: 'pointer',
    color: state.isFocused ? '#585858' : '#ccc',
    fontWeight: 500,
  }),
  // Add more custom styles here if needed
};

const eventOptions = [
  // Define your options here
];

const SelectComponent = () => {
  return (
    <Select
      defaultValue={[]}
      name="events"
      options={eventOptions}
      styles={selectionStyles}
      placeholder="Select Category"
      components={{ ClearIndicator }}
      classNamePrefix="select"
    />
  );
};

export default SelectComponent;
© www.soinside.com 2019 - 2024. All rights reserved.