【问题标题】:ReactJS: How to perform multiple selection in Dropdown?ReactJS:如何在下拉菜单中执行多项选择?
【发布时间】:2019-11-08 11:21:06
【问题描述】:

我已经为单个选择开发了下拉选择。现在我想将其设为多项选择。如何在 API 响应中传递多个 id。 ?

我的单选工作代码是这样的:

class Xyz extends React.Component {
    constructor(props) {
        super(props);
        this.state = {id: props.defaultValue.id, name: props.defaultValue.name, open: true};
    }
    updateData = () => {
        console.log(this.state.id)
        this.props.onUpdate({id: this.state.id, name: this.state.name});
        api.request({url: `/api-route/${this.props.id}`, method: 'put', data: {[this.field]: this.state.id} })
            .then(res => (`${this.field} have been updated`)
            .catch(er => console.log(er));
    }
    render() {
        return (
            <React.Fragment>
                <select
                    multiple={true}
                    defaultValue={[this.props.defaultValue.id]}
                    onChange={ev => this.setState({ id: ev.target.value, name: ev.nativeEvent.target[ev.nativeEvent.target.selectedIndex].text })}>
                    {this.props[this.field].map((name, index) => <option key={index} value={index}>{name}</option>)}
                </select>
                <button type='button' className='btn btn-primary' onClick={this.updateData}>Save</button>
            </React.Fragment>
        );
    }
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    对于多选,你可以试试下面的插件

    https://github.com/JedWatson/react-select

    const options = [];  
    
     class App extends React.Component {
      state = {
        selectedOption: null,
      }
    
      constructor(props) {
        super(props);
        this.props[this.field].map((name, index) => {
          options.push({ value: index, label: name });
        });
      }
      handleChange = (selectedOption) => {
        this.setState({ selectedOption });
        console.log(`Option selected:`, selectedOption);
      }
      render() {
        const { selectedOption } = this.state;
    
        return (
          <Select
            value={selectedOption}
            onChange={this.handleChange}
            options={options}
            isMulti
          />
        );
      }
    }
    

    要了解有关 react-select 的更多信息,请查看以下帖子

    https://medium.com/@nidhinkumar/react-select-852e90d549df

    【讨论】:

    • 在那种情况下我怎么能像这样传递选项属性&lt;option key={index} value={index}&gt;{name}&lt;/option&gt;
    • @aananddham 将由插件处理
    • 好的,那么我应该在options={options} 中传递什么?它如何获得{name} 值?
    • 我已在您的媒体博客上查看了您的更新答案;你能用我的代码更新它吗?
    猜你喜欢
    • 2018-04-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2020-02-10
    • 2011-03-08
    • 2016-01-06
    • 2019-03-24
    相关资源
    最近更新 更多