简体   繁体   English

使用类似于 onSelect() 的 onChange() 将 select 值打印到控制台

[英]Print the select value to console with onChange() similar to onSelect()

I am trying to print the value of the select to the console.我正在尝试将 select 的值打印到控制台。 I was able to do this in an onSelect() method however the onChange() method seems to return an empty object.我能够在 onSelect() 方法中执行此操作,但是 onChange() 方法似乎返回一个空的 object。

My unsuccessful attempt at the onChange() method:我在 onChange() 方法上的失败尝试:

<Form.Group controlId="exampleForm.ControlSelect1">
  <Form.Label>Example select</Form.Label>
  <Form.Control as="select" onChange={function(obj){console.log(obj)}}>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </Form.Control>
</Form.Group>

Example) If user selects 'Link 1' from the select, the onSelect() method would print the eventKey 'Link1' to the console.示例)如果用户从 select 中选择“Link 1”,则 onSelect() 方法会将 eventKey 'Link1' 打印到控制台。

<DropdownButton id="dropdown-item-button" title="Links" onSelect={function(evt){console.log(evt)}}>
  <Dropdown.Item as="button" eventKey='Link1'>Link 1</Dropdown.Item>
  <Dropdown.Item as="button" eventKey='Link2'>Link 2</Dropdown.Item>
  <Dropdown.Item as="button" eventKey='Link3'>Link 3</Dropdown.Item>
</DropdownButton>  

In order to ger the value you need to check the target of the event.为了获取值,您需要检查事件的目标。 I have done this with your first example.我已经用你的第一个例子做到了这一点。

<Form.Group controlId="exampleForm.ControlSelect1">
  <Form.Label>Example select</Form.Label>
  <Form.Control as="select" onChange={(obj) => console.log(obj.target.value)}>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </Form.Control>
</Form.Group>

What this does is gets the caller of the event which is your select, then gets the selected value from that.这样做是获取事件的调用者,即您的 select,然后从中获取选定的值。

EDIT: I should mention I've used a lambda function within the Select control however this works just as effectively:编辑:我应该提到我在 Select 控件中使用了 lambda function 控件,但这同样有效:

onChange={function(obj) {
    console.log(obj.target.value);
  }
}

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

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