简体   繁体   中英

Get multiple values from the same select dropdown form field in React

I currently have a React Material form with a select dropdown, in which I map over an array of objects and display the name field as each option. I've currently set the option's value attribute to the object's name (cpuParent.name). However, the same object also has a wattage field (cpuParent.wattage), the value of which I also need. Is there a way that I can get both the name and the wattage of the object from the same dropdown field? I've copied and pasted the relevant snippets of my code below - the component is a class component:

Within the class component, but outside the render method:

constructor(props) {
    super(props);

    this.state = {
        calculator: {
            cpuParent: '',
            cpuChild: 0
        }
    }
}

handleChange = name => event => {
    this.setState({
        calculator: {
            ...this.state.calculator,
            [name]: event.target.value
        }
    });
};

Inside the render method:

// Destructure the state
const {calculator: {cpuParent, cpuChild}} = this.state;

// Destructure the props
const {classes, cpuParents} = this.props;

<FormControl className={classes.formControl}>
    <NativeSelect
        value={cpuParent}
        onChange={this.handleChange('cpuParent')}
        inputProps={{'aria-label': 'CPU Parent'}}
    >
        <option value="">Select Brand</option>
        {
            cpuParents.map(cpuParent => (
                <option key={cpuParent.id} value={cpuParent.name}>
                    {cpuParent.name}
                </option>
            ))
        }
    </NativeSelect>
</FormControl>

您无法同时获得名称和功率值,但它们是一个技巧:您可以将名称和功率与选项值中的特定字符连接起来,例如value={cpuParent.name + "_" + cpuParent.wattage }并读取handleChange的值事件函数通过拆分像 let value = event.target.value.split('_')

You can get whole object just change your option value to whole object

<option key={cpuParent.id} value={cpuParent}>
                    {cpuParent.name}
                </option>

Now the label will display name, but value will hold whole object item. you can access whichever value you need.

And you can access the attributes using

  [name]: event.target.value['name']
  [name]: event.target.value['wattage']

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