简体   繁体   English

从 React 中的同一个选择下拉表单字段中获取多个值

[英]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.我目前有一个带有选择下拉列表的 React Material 表单,我在其中映射了一组对象并将名称字段显示为每个选项。 I've currently set the option's value attribute to the object's name (cpuParent.name).我目前已将选项的 value 属性设置为对象的名称 (cpuParent.name)。 However, the same object also has a wattage field (cpuParent.wattage), the value of which I also need.但是,同一个对象也有一个瓦数字段(cpuParent.wattage),我也需要它的值。 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:在类组件内,但在 render 方法之外:

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']

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

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