简体   繁体   中英

How to pass a key value into the onchange handler for a select dropdown

I'm mapping an array[key,val] to dynamically create dropdowns. I want to pass the key from the select onChange handler so I can store the selected value in the correct index in the array. How do I pass the key.

 AdditionQueryArray.map((val, key) => {
    <Select
        onChange={this.AdditionalFieldHandleChange(key)}
        isMulti
        options={this.state.fieldOptions}
    />
}

AdditionalFieldHandleChange = (selectedOption,key) => {// saving selected option in array by key here}

I think this is the answer you need: React js onClick can't pass value to method

example:

AdditionQueryArray.map((val, key) => {
    <Select
        onChange={() => this.AdditionalFieldHandleChange(key)}
        isMulti
        options={this.state.fieldOptions}
    />
}

AdditionalFieldHandleChange = (selectedOption,key) => {// saving selected option in array by key here}

Maybe add the "val" option to the arguments because you have two arguments in your function definition?

You could do something like this:

AdditionQueryArray.map((val, key) => {
    <Select
        onChange={this.AdditionalFieldHandleChange(key, event)}
        isMulti
        options={this.state.fieldOptions}
    />
}

AdditionalFieldHandleChange = (key, event) => {
const val = event.target.value //this will be the selected value
// saving selected option in array by key here
}

This way can be used for all types of form fields, be it input or selections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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