Javascript 如何在 ReactJS 中获取下拉菜单的选定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29108779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:52:01  来源:igfitidea点击:

How to get selected value of a dropdown menu in ReactJS

javascriptselectdrop-down-menumenureactjs

提问by BlueElixir

I'm using react and I want to get the value of the selected option of a dropdown in react but I don't know how. Any suggestions? thanks! My dropdown is just a select like:

我正在使用 react,我想获取 react 中下拉列表的选定选项的值,但我不知道如何。有什么建议?谢谢!我的下拉列表只是一个选择:

            <select id = "dropdown">
                <option value="N/A">N/A</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
            </select>

回答by Max Heiber

The code in the rendermethod represents the component at any given time. If you do something like this, the user won't be able to make selections using the form control:

render方法中的代码表示任何给定时间的组件。如果你做这样的事情,用户将无法使用表单控件进行选择:

<select value="Radish">
  <option value="Orange">Orange</option>
  <option value="Radish">Radish</option>
  <option value="Cherry">Cherry</option>
</select>

So there are two solutions for working with forms controls:

因此,有两种使用表单控件的解决方案:

  1. Controlled ComponentsUse component stateto reflect the user's selections. This provides the most control, since any changes you make to statewill be reflected in the component's rendering:
  1. 受控组件使用组件state来反映用户的选择。这提供了最多的控制,因为您所做的任何更改state都将反映在组件的渲染中:

example:

例子:

var FruitSelector = React.createClass({
    getInitialState:function(){
      return {selectValue:'Radish'};
  },
    handleChange:function(e){
    this.setState({selectValue:e.target.value});
  },
  render: function() {
    var message='You selected '+this.state.selectValue;
    return (
      <div>
      <select 
        value={this.state.selectValue} 
        onChange={this.handleChange} 
      >
       <option value="Orange">Orange</option>
        <option value="Radish">Radish</option>
        <option value="Cherry">Cherry</option>
      </select>
      <p>{message}</p>
      </div>        
    );
  }
});

React.render(<FruitSelector name="World" />, document.body);

JSFiddle: http://jsfiddle.net/xe5ypghv/

JSFiddle:http: //jsfiddle.net/xe5ypghv/

  1. Uncontrolled ComponentsThe other option is to not control the value and simply respond to onChangeevents. In this case you can use the defaultValueprop to set an initial value.

    <div>
     <select defaultValue={this.state.selectValue} 
     onChange={this.handleChange} 
     >
        <option value="Orange">Orange</option>
        <option value="Radish">Radish</option>
        <option value="Cherry">Cherry</option>
      </select>
      <p>{message}</p>
      </div>       
    
  1. 不受控制的组件另一种选择是不控制值并简单地响应onChange事件。在这种情况下,您可以使用defaultValueprop 设置初始值。

    <div>
     <select defaultValue={this.state.selectValue} 
     onChange={this.handleChange} 
     >
        <option value="Orange">Orange</option>
        <option value="Radish">Radish</option>
        <option value="Cherry">Cherry</option>
      </select>
      <p>{message}</p>
      </div>       
    

http://jsfiddle.net/kb3gN/10396/

http://jsfiddle.net/kb3gN/10396/

The docs for this are great: http://facebook.github.io/react/docs/forms.htmland also show how to work with multiple selections.

这方面的文档很棒:http: //facebook.github.io/react/docs/forms.html并且还展示了如何使用多个选择。

UPDATE

更新

A variant of Option 1 (using a controlled component) is to use Reduxand React-Reduxto create a container component. This involves connectand a mapStateToPropsfunction, which is easier than it sounds but probably overkill if you're just starting out.

选项 1(使用受控组件)的一个变体是使用ReduxReact-Redux创建容器组件。这涉及到connect一个mapStateToProps函数,这比听起来容易,但如果您刚刚开始,可能会过分矫枉过正。

回答by Shubham Khatri

Implement your Dropdown as

将您的下拉菜单实现为

<select id = "dropdown" ref = {(input)=> this.menu = input}>
    <option value="N/A">N/A</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

Now, to obtain the selected option value of the dropdown menu just use:

现在,要获取下拉菜单的选定选项值,只需使用:

let res = this.menu.value;

回答by Karén

Just use onChangeevent of the <select>object. Selected value is in e.target.valuethen.

只需使用对象的onChange事件<select>。选择的值在e.target.value那时。

By the way, it's a bad practice to use id="...". It's better to use ref=">.."http://facebook.github.io/react/docs/more-about-refs.html

顺便说一句,使用id="...". 最好使用ref=">.."http://facebook.github.io/react/docs/more-about-refs.html

回答by ABHIJEET KHIRE

As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList 1 remember you will always get the result as option value and not the dropdown text which is displayed on the screen

对于前端开发人员来说,很多时候我们都在处理我们必须处理下拉列表的表单,我们必须使用所选下拉列表的值来执行某些操作或在服务器上发送值,这很简单要在 HTML 中编写简单的下拉列表,只需在下拉列表中放置一个用于选择的 onChange 方法,每当用户更改下拉列表的值时将该值设置为 state,这样您就可以在 AvFeaturedPlayList 中轻松访问它 1 请记住,您将始终获得结果作为选项值而不是屏幕上显示的下拉文本

import React, { Component } from "react";
import { Server } from "net";

class InlineStyle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectValue: ""
    };

    this.handleDropdownChange = this.handleDropdownChange.bind(this);
  }

  handleDropdownChange(e) {
    this.setState({ selectValue: e.target.value });
  }

  render() {
    return (
      <div>
        <div>
          <div>
            <select id="dropdown" onChange={this.handleDropdownChange}>
              <option value="N/A">N/A</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
            </select>
          </div>

          <div>Selected value is : {this.state.selectValue}</div>
        </div>
      </div>
    );
  }
}
export default InlineStyle;

回答by jerryurenaa

You can handle it all within the same function as following

您可以在以下相同的功能中处理所有这些

<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>

  <option value="5">5 dollars</option>
  <option value="10">10 dollars</option>
                                         
</select>

as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!

正如您所看到的,当用户选择一个选项时,它将设置一个状态并获取所选事件的值,而无需进一步编码!

回答by Arindam Mojumder

It is as simple as that. You just need to use "value"attributes instead of "defaultValue"or you can keep both if a pre-selected feature is there.

它是如此简单。您只需要使用“value”属性而不是“defaultValue”,或者如果存在预先选择的功能,则可以同时保留两者。

 ....
const [currentValue, setCurrentValue] = useState(2);
<select id = "dropdown" value={currentValue} defaultValue={currentValue}>
     <option value="N/A">N/A</option>
     <option value="1">1</option>
     <option value="2">2</option>
     <option value="3">3</option>
     <option value="4">4</option>
  </select>
.....

setTimeut(()=> {
 setCurrentValue(4);
}, 4000);

In this case, after 4 secs the dropdown will be auto-selected with option 4.

在这种情况下,4 秒后将使用选项 4 自动选择下拉列表。

回答by fahimeh ahmadi

import React from 'react';
import Select from 'react-select';

const options = [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' },
];

class App extends React.Component {
  state = {
    selectedOption: null,
  };
  handleChange = selectedOption => {
    this.setState({ selectedOption });
    console.log(`Option selected:`, selectedOption);
  };
  render() {
    const { selectedOption } = this.state;

    return (
      <Select
        value={selectedOption}
        onChange={this.handleChange}
        options={options}
      />
    );
  }
}

And you can check it out on this site.

你可以在这个网站上查看。