简体   繁体   English

如何在反应js中获取所选选项的ID

[英]How to get id of selected option in react js

I have created a very simple select box.我创建了一个非常简单的 select 盒子。

<FormGroup>
  <label for='category' className='label'>Category</label>
  <select ref="categoryName">
    {categoriesList}
  </select>
</FormGroup>

and

let categoriesList = categories.map(category =>
  <option id={category.id}>
      {category.type}
   </option>
 )

I'm trying to figure out how I can get the value of 'id' attribute of the option that's selected in the dropdown, I want to use this value for some further processing.我试图弄清楚如何获取在下拉列表中选择的选项的 'id' 属性的值,我想使用该值进行进一步处理。 please advise.请指教。 thanks谢谢

Using React, you don't need to do this with refs per se, you do have the state.使用 React,您不需要使用 refs 本身来执行此操作,您确实拥有 state。

Take a look at this example:看看这个例子:

  const [selectedItem, setSelectedItem] = useState()

  const handleSelect = (event) => {
    setSelectedItem(event.target.value)
  }

  console.log(selectedItem) // Your Selected Option

  return (
    <FormGroup>
      <label htmlFor="category" className="label">
        Category
      </label>
      <select onChange={handleSelect}>{categoriesList}</select>
    </FormGroup>
  )

I am utilizing React's useState module here.我在这里使用 React 的useState模块。 It is how we manage state in the newer versions of React.这就是我们在较新版本的 React 中管理 state 的方式。 You might be more familiar with this.setState , where the example would be something more like this:您可能更熟悉this.setState ,其中的示例更像这样:

constructor() {
    super()

    this.state = {
      selectedValue: '',
    }
  }

  handleSelect = (event) => {
    this.setState({
      selectedValue: event.target.value,
    })
  }

  console.log(this.state.selectedValue) // Your selected value

  render() {
    return (
      <FormGroup>
        <label htmlFor="category" className="label">
          Category
        </label>
        <select onChange={handleSelect}>{categoriesList}</select>
      </FormGroup>
    )
  }

Keep in mind that I don't see the full file where your code is, so I don't know if your component is made using Classes, like:请记住,我没有看到您的代码所在的完整文件,所以我不知道您的组件是否是使用类制作的,例如:

Class App extends React.Component or const App = () => {} Class App extends React.Componentconst App = () => {}

Depending on this definition of your component, you should decide which method to use.根据组件的此定义,您应该决定使用哪种方法。 If it is Class, use the 2nd options, if it is not, use the 1st one.如果是 Class,使用第二个选项,如果不是,使用第一个选项。

As for perserving the id , i Would modify your list of selects like this:至于保留id ,我会像这样修改您的选择列表:

let categoriesList = categories.map(category =>
  <option value={category.id} id={category.id}>
      {category.type}
   </option>
 )

this way, the saved state will have category.id and you will be able to further process with it.这样,保存的 state 将具有category.id ,您将能够进一步处理它。

You can add an onChange event handler to the select which checks for the selected index and retrieve the id from the selected option.您可以将onChange事件处理程序添加到 select 以检查所选索引并从所选选项中检索 id。

onChangeHandler = (e) => {
  const index = e.target.selectedIndex;
  const el = e.target.childNodes[index]
  const option =  el.getAttribute('id');  
}

<FormGroup>
  <label for='category' className='label'>Category</label>
  <select onChange={onChangeHandler}>
      {categories.map(category =>
          <option id={category.id}>
             {category.type}
          </option>
      )}
  </select>
</FormGroup>

Ideally you should try and avoid getting state from the DOM.理想情况下,您应该尽量避免从 DOM 获取 state。

React works really well if you control state, and leave React to render your state.如果你控制 state,React 工作得非常好,让 React 渲染你的 state。

Below is a simple example, basically all I do is store the state index into an array,.下面是一个简单的例子,基本上我所做的就是将 state 索引存储到一个数组中。 And when I update this, the React view will update accordingly.当我更新它时,React 视图会相应地更新。 How you store state is then totally up to you, and not the DOM.如何存储 state 完全取决于您,而不是 DOM。

 const {useState} = React; const lookup = [ {id: 1, value: 'one'}, {id: 2, value: 'two'}, {id: 3, value: 'three'} ]; function List() { const [selected, setSelected] = useState(-1); const value = selected;== -1 && lookup[selected]. return <div> <select onChange={(e) => setSelected(e.target.value)} value={selected}> <option>Please Selected an option</option> {lookup,map((m. ix) => { return <option key={m.id} value={ix} > {m;value} </option> })}: </select> {value && <div style={{marginTop. "2rem"}}> You selected ID <span>{value.id}</span> value <span>{value;value}</span> </div>} </div>. } ReactDOM,render(<List/>. document;querySelector('#mount'));
 body, select, option { font-size: 20px; } select, option { padding: 0.5rem; } body { padding: 2rem; } span { font-weight: bold; margin: 1em; background-color: yellow; border: 1px solid black; padding: 1em 1.5rem; border-radius: 50%; }
 <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="mount"/>

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

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