react-select.js 多选防止默认x按钮或删除

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

为什么我使用反应选择进行多重选择。我希望阻止默认删除包生成的关闭选项。请参阅随附的打印屏幕

死图像

    function renderer(obj, index){
      return <span name='name'>{obj.value}</span>
    }
    export default  class Select extends Component {
      componentDidMount(){
        this.refs.stateSelect.focus();
      }

      render() {
       const {props} = this;
       const options = props.options;

       return <Select
        {...props}
        allowCreate={true}
        multi={true}
        ref="stateSelect"
        tabIndex={0}
        autofocus
        valueKey='value'
        clearable={false}
        value={props.value}
        options={options}
        valueRenderer = {renderer}
        optionRenderer={renderer}
        onChange={this.onChange}
      />;
    }

     onChange(value, selectedOptions){
       this.props.onSelect && this.props.onSelect(selectedOptions);
     }
    }
reactjs react-select
3个回答
2
投票

我认为目前使用 Select 控件不可能做到这一点,除非您想分叉代码并修改它。

一种不优雅的解决方案是在 onChange 侦听器中,将新值与以前的值进行比较,如果某些项目较少,则恢复旧值。如果在您的用例中,您想让用户清除整个列表,但一次不想清除一个值,则可以让 onChange 接受新值(如果它为空)。 像这样的东西 -

export default  class Select extends Component {
  componentDidMount(){
    this.refs.stateSelect.focus();
  }

  componentWillReceiveProps(newProps){
    this.setState({"value":newProps.value}});
  }

  render() {
   const {props} = this;
   const options = props.options;

   return 
   (<Select
    {...props}
    allowCreate={true}
    multi={true}
    ref="stateSelect"
    tabIndex={0}
    autofocus
    valueKey='value'
    clearable={false}
    value={this.state.value}
    options={options}
    valueRenderer = {renderer}
    optionRenderer={renderer}
    onChange={this.onChange}
    />);
}

 onChange(value, selectedOptions){
    if (this.value.length > this.state.value.length
        || this.value == "" //comment this line if you don't want user to clear the entire select
        ){
      this.setState({"value":value});
    }
   this.props.onSelect && this.props.onSelect(selectedOptions);
 }
}

0
投票

可以使用样式值

multiValueRemove
来实现

const selectStyle = {
  multiValueRemove: (style, state) => {
    console.log('multi value remove', state, style);
    return {
      ...style,
      ...(state.data?.isDisabled
        ? {
            visibility: 'hidden',
            width: '4px',
          }
        : {}),
    };
  },

};

return <Select styles={selectStyle} />

0
投票

对于那些想要完全删除“x”(“清除所有”)按钮的人,它似乎与其他答案不同,它可能在新版本中发生了变化。
下面的解决方案使用:

"react-select": "^5.2.1",

现在可以使用道具

isClearable
;如果未提供,则默认为
true
如果 (文档)

选择值是否可清除

<Select
  isDisabled={isDisabled}
  isMulti={isMulti}
  options={options}
  value={value ? value : null}
  menuPlacement="auto"
  // ... 
  isClearable={false}
/>

添加

isClearable={false}
将删除“x”(“全部清除”)按钮(参见下图中的第二个选择)

© www.soinside.com 2019 - 2024. All rights reserved.