简体   繁体   中英

How to add the input field inside the select option using ant design and react

I created select option using ant design.But I need create editable cell inside the select option.

This my select option code

<Select
  showSearch
  style={{ width: 400 }}
  placeholder="Select a Bank"
  optionFilterProp="children"
  onChange={this.handleChange.bind(this)}
>
  <option value="1">Bank1</option>
  <option value="2"> Bank2</option>
  <option value="3"> Bank3</option>
</Select> 

And onChange functions is

handleChange(value) {
  console.log(`selected ${value}`);
  this.setState({
    bank:value,
  });
}

Can you help me?

I suppose the question is whether or not this is an editable list.

The Select component has a mode prop that can be used to change the functionality with the following options:

'default' | 'multiple' | 'tags' | 'combobox'

Using the tags mode would allow you to add and remove items and generate a tokenized list when the form is submitted.

If you are looking at a fixed list and then wanting to create new items to add to the list:

If you want to be able to add new items to the list, this doesn't exist currently, as far as I am aware.

You may be able to refashion something from the Ant Design Pro components, or otherwise come up with a solution where:

  1. when "create" is selected, you toggle the Select for an Input
  2. when the input is submitted/blurred update the Options list, toggle the Select/Input once more and submit the value to the back-end.

I hope this helps.

You don't need to do that actually. All you need to do is to use component state and two simple callback functions ant design provides for select.

So let's assume you need to allow users not to also search for existing values inside a Select but if it didn't exist they can choose a new one. So here's what I'd do:

Inside render() method:

<Select
    showSearch
    value={this.title}
    filterOption={true}
    onSearch={this.handleSearch}
    onFocus={this.handleFocus}
    style={{ width: "100%" }}>
    {this.titles.map((title) => (
      <Select.Option key={title}>{title}</Select.Option>
    ))}
</Select>

Where this.titles = ["something", "else"] .

Then Inside this.handleSearch and this.handleFocus I'd write:

protected handleSearch = (value: string) => {
    this.setState({ titles: value && value !== "" ? [...this.titles, value] : fileTitles });
};

protected handleFocus = () => {
    this.setState({ this.titles });
};

What we're basically doing is to populate the options we're iterating over inside the Select with this.titles in the state of the component itself (don't confuse it with Redux or MobX) when user opens the selector and once user searches for anything that would be added to options as well. With this approach you won't need an input or a switch to show/hide inputs. Hope it helps.

You could use another modal to input the additional value.

Check this : https://codesandbox.io/s/antdselectaddoption-7fov7

Code from mamsoudi throws Errors, so i took his idea and made my own component that i'm sharing with you.

import React from 'react';
import {Select} from "antd";

class FieldSelectAndCustomText extends React.Component {
    constructor(props) {
        super(props);
        this.initialTitles = ["something", "else"];
        this.state = {
            titles: this.initialTitles,
            currentValue: null,
        };
    }
    handleSearch = (value) => {
        const titles = this.state.titles;
        for (let i = 0; i < titles.length; i++) {
            const isSearchValueInState = new RegExp(value).test(titles[i]);
            if (!isSearchValueInState) {
                this.setState({
                    titles: [...this.initialTitles, value],
                    currentValue: value
                });
                break;
            }
        }
    };

    handleChange = (value) => {
        this.setState(prev => ({...prev, currentValue: value}));
    }

    render () {
        return (
            <div>
                <Select
                    showSearch
                    value={this.state.currentValue}
                    filterOption={true}
                    onSearch={this.handleSearch}
                    onChange={this.handleChange}
                    onFocus={this.handleFocus}
                    style={{ width: "100%" }}>
                    {this.state.titles.map((title) => (
                        <Select.Option value={title} key={title}>{title}</Select.Option>
                    ))}
                </Select>
            </div>
        );
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM