简体   繁体   English

如何在 ReactJS 中处理多选表单

[英]How handle multiple select form in ReactJS

I try to handle a multiple form select option , in ReactJS.我尝试在 ReactJS 中处理多表单选择选项 I have tried to be inspire of javascript classic code to handle that, but I fail.我试图受到 javascript 经典代码的启发来处理这个问题,但我失败了。

My code just don't send me the values selected.我的代码只是不向我发送所选的值。 How handle that ?怎么处理?

Here my code :这是我的代码:

  class ChooseYourCharacter extends React.Component {

      constructor(props) {
        super(props);
        this.state = {value: 'coconut'};

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }

      handleChange(event) {
        this.setState({value: event.option});
      }

      handleSubmit(event) {
        alert('Your favorite flavor is: ' + this.state.value);
        event.preventDefault();
      }

      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            <label>
              Pick your favorite La Croix flavor:
              <select multiple={true} value={this.state.value} onChange={this.handleChange}>
                <option value="grapefruit">Grapefruit</option>
                <option value="lime">Lime</option>
                <option value="coconut">Coconut</option>
                <option value="mango">Mango</option>
              </select>
            </label>
            <input type="submit" value="Submit" />
          </form>
        );
      }
    }
    ReactDOM.render(
             <ChooseYourCharacter/>,
             document.getElementById('root')
    )

Of my basic understanding, when you try to handle a Select form element in reactJS you generates an object in HTMLOptionsCollection.根据我的基本理解,当您尝试在 reactJS 中处理Select 表单元素时,您会在 HTMLOptionsCollection 中生成一个对象。

The fundamental root to this object methods and properties is e.target.options .此对象方法和属性的基本根是e.target.options

Your items are stored in e.target.options.value property.您的项目存储在 e.target.options.value 属性中。

To access to a value stored in the options.value object, you can use the [i] loop value, hence e.target.options[i].value property.要访问存储在 options.value 对象中的值,您可以使用 [i] 循环值,因此 e.target.options[i].value 属性。

The e.target.options[i].value return strings data types. e.target.options[i].value 返回字符串数据类型。

Following what I have just said, I assume the objects are stored respecting a number increasing convention as following :按照我刚才所说的,我假设对象是按照数字递增的约定存储的,如下所示:

e.target.options[i].value where { [i] : value, [i +1] : value (...)}... e.target.options[i].value where { [i] : value, [i +1] : value (...)}...

By using e.target.options[i].selected you can control if there is a value stored at a specific location.通过使用 e.target.options[i].selected 您可以控制是否在特定位置存储了值。

e.target.options[i].selected return you a boolean value, useful to handle the code flow. e.target.options[i].selected 返回一个布尔值,用于处理代码流。

It's up to you now.现在就看你了。


Here my code to handle multiple select form in JSX with javascript code :这里我的代码使用 javascript 代码处理 JSX 中的多个选择表单:

// Create the React Component


    class ChooseYourCharacter extends React.Component {

          // Set the constructor
          constructor(props) {
            super(props);
            this.state = {value: 'coconut'};

            // bind the functions
            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
          }

          // extract the value to fluently setState the DOM
          handleChange (e) {
            var options = e.target.options;
            var value = [];
            for (var i = 0, l = options.length; i < l; i++) {
              if (options[i].selected) {
                value.push(options[i].value);
              }
            }
            this.setState({value: value});
          }

          // display in client-side the values choosen
          handleSubmit() {
             alert("you have choose :" + this.state.value);

         }


    (...)

Here is how to get the options selected by the user using a functional component and the useState hook rather than a class component:以下是如何使用功能组件和 useState 钩子而不是类组件获取用户选择的选项:

import React, { useState } from "react";

const ChooseYourCharacter = function(props) {
    const [selectedFlavors, setSelectedFlavors] = useState([]);

    const handleSelect = function(selectedItems) {
        const flavors = [];
        for (let i=0; i<selectedItems.length; i++) {
            flavors.push(selectedItems[i].value);
        }
        setSelectedFlavors(flavors);
    }

    return (
        <form>
            <select multiple={true} value={selectedFlavors} onChange={(e)=> {handleSelect(e.target.selectedOptions)}}>
                <option value="grapefruit">Grapefruit</option>
                <option value="lime">Lime</option>
                <option value="coconut">Coconut</option>
                <option value="mango">Mango</option>
            </select>
        </form>
    );
};

export default ChooseYourCharacter;

Currently learning React and I noticed this same code on the reactjs.org site .目前正在学习 React,我在reactjs.org 站点上注意到了相同的代码。 Below is my solution for handling multiple selected options.以下是我处理多个选定选项的解决方案。

  1. in the constructor, use an array for the initial value for 'value' in the state在构造函数中,使用数组作为状态中“值”的初始值
  2. in the handleChange method, convert the event target's selectedOptions (HTMLOptionsCollection - array-like) to an array using Array.from(), and use a mapping function to get the value from each item在handleChange方法中,使用Array.from()将事件目标的selectedOptions(HTMLOptionsCollection-array-like)转换为数组,并使用映射函数从每一项中获取值

 class ChooseYourCharacter extends React.Component { constructor(props) { super(props); //this.state = {value: 'coconut'}; this.state = {value: ['coconut']}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { //this.setState({value: event.option}); this.setState({value: Array.from(event.target.selectedOptions, (item) => item.value)}); } handleSubmit(event) { alert('Your favorite flavor is: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Pick your favorite La Croix flavor: <select multiple={true} value={this.state.value} onChange={this.handleChange}> <option value="grapefruit">Grapefruit</option> <option value="lime">Lime</option> <option value="coconut">Coconut</option> <option value="mango">Mango</option> </select> </label> <input type="submit" value="Submit" /> </form> ); } } ReactDOM.render( <ChooseYourCharacter/>, document.getElementById('root') )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>

As you are using multi-select you should declare your state variable as an array当您使用多选时,您应该将状态变量声明为数组

  constructor(props) {
    super(props);
    this.state = {value: []};//This should be an array

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

I have created a blog for reactjs form posting with multi select control.我创建了一个带有多选控件的 reactjs 表单发布博客。 You may go here for more details https://handyopinion.com/git-commands-cheat-sheet/你可以去这里了解更多详情https://handyopinion.com/git-commands-cheat-sheet/

I am using react bootstrap 4 here我在这里使用 react bootstrap 4

   <Form.Group >
          <Form.Label>Form Label</Form.Label>
          <Form.Control
            as="select"
            multiple
            // value={formCatState}
            onChange={(event) => {
              let target = event.target as HTMLSelectElement
              console.log(target.selectedOptions);
            }}
          >
            <option>example cat 1</option>
            <option>Example cat 2</option>
            <option>Example cat 3</option>
            <option>Example cat 4</option>
          </Form.Control>
            <Form.Text muted> hold ctrl or command for multiple select</Form.Text>
        </Form.Group>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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