【问题标题】:What is the best way to get the selected value from a React-Select component?从 React-Select 组件中获取所选值的最佳方法是什么?
【发布时间】:2020-02-25 15:49:02
【问题描述】:

我正在使用 react select 创建选项下拉列表。我想访问下拉菜单上的标签,但也想访问与数据关联的值。例如:

import Select from 'react-select'


let options = [
 {
 label: Small,
 change: -3
 },
 {
 label: Medium,
 change: 0
 }
]

<Select id={"options"} defaultValue={options[0]} options={options} />

let selectedChange = // How can I access the change property?
let selectedLabel = document.querySelector(`#options`).textContent // This is how I have been getting the proper label

<button onClick={console.log(selectedChange, selectedLabel)}></button>

我想通过将选项更改值添加到默认价格来更改项目的显示成本,但我只想在选择中显示标签。

【问题讨论】:

  • 哦,我看到它内置在 onChange 中,非常感谢。在测试中,我看到它返回了与输入数据关联的所有值,因此它返回了标签、值和更改。
  • 修正了我之前的评论:选项的默认格式是 { label: 'somelabel', value: 'someValue' } 。选择选项后,Select 987654324 @将返回所选对象(即{ label, value, etc })。 span>

标签: javascript reactjs jsx react-select


【解决方案1】:

React-Select onChange 属性接受一个方法,并接收选定的项目以及正在执行的操作:

function(
  One of<
    Object,
    Array<Object>,
    null,
    undefined
  >,
  {
    action required One of<
      "select-option",
      "deselect-option",
      "remove-value",
      "pop-value",
      "set-value",
      "clear",
      "create-option"
    >
  }
  ) => undefined

作为开发人员,您可以选择如何处理从此方法返回的对象。例如,您可以查看此Codesandbox

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多