代码之家  ›  专栏  ›  技术社区  ›  HoCo_

如何在ReactJS中处理多个select表单

  •  8
  • HoCo_  · 技术社区  · 8 年前

    我试着处理 多表单选择选项 ,在ReactJS中。我曾试图从javascript经典代码中获得灵感来处理这个问题,但我失败了。

    我的代码只是不向我发送所选的值。如何处理?

    这里是我的代码:

      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')
        )
    
    5 回复  |  直到 8 年前
        1
  •  11
  •   Dorklord    6 年前

    我的基本理解是 选择表单元素 在reactJS中,您在HTMLOptionsCollection中生成一个对象。

    此对象方法和属性的基本根是 e、 目标。选项

    您的项目存储在e.target中。选项。value属性。

    访问存储在选项中的值。value对象,可以使用[i]循环值,因此可以使用e.target。选项[一]。value属性。

    e.目标。选项[一]。值返回字符串数据类型。

    按照我刚才所说的,我假设对象是按照以下递增的约定存储的:

    e、 目标。选项[一]。值,其中{[i]:值,[i+1]:值(…)}。。。

    通过使用e.target。选项[一]。选中此选项,可以控制是否有值存储在特定位置。

    e、 目标。选项[一]。选中此选项将返回一个布尔值,这对处理代码流很有用。

    现在由你决定。


    下面是我用javascript代码在JSX中处理多个select表单的代码:

    // 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);
    
             }
    
    
        (...)
    
        2
  •  9
  •   Ryan Ellingson    5 年前

    下面是如何获得用户使用功能组件和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;
    
        3
  •  8
  •   Rick S.    7 年前

    目前正在学习React,我在 reactjs.org site 。下面是我处理多个选定选项的解决方案。

    1. 在构造函数中,使用数组作为状态中“value”的初始值
    2. 在handleChange方法中,将事件目标的selectedOptions(HTMLOptionsCollection-array-like)转换为使用array的数组。from(),并使用映射函数从每个项中获取值

    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>
        4
  •  1
  •   Ahmed Bilal    6 年前

    使用multi-select时,应将状态变量声明为数组

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

    我已经创建了一个带有多选控件的reactjs表单发布博客。你可以到这里了解更多详情 https://handyopinion.com/git-commands-cheat-sheet/

        5
  •  0
  •   Mohammed    5 年前

    我在这里使用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>