Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

reactjs - How to get the id of the selected item from a dropdown list?

I can get the selected item's value (name), but the is an id and url fro each item beside the name. How can I get those?

<select
class = "form-control"
onChange = {
        this.handleSelect
    } >
    {
        allMemesImg.map(item => ( <
            option key = {
                item.id
            } > {
                item.name
            } <
            /option>
        ))
    } 
 </select>




handleSelect = event => {
    this.setState({
        value: event.target.value,
    });
    alert(event.target.value);
}
question from:https://stackoverflow.com/questions/65915424/how-to-get-the-id-of-the-selected-item-from-a-dropdown-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to add value at your option.

handleSelect =(e)=>{
 if (e.target.value !== '') {    
    this.setState({
     value: e.target.value
   })
}
    


<select onChange={this.handleSelect}>
        {allMemesImg.map((item, index) =>
             <option key={index} value={item.id}>
                 {item.name}
             </option>)}
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...