【问题标题】:Get multiple values from the same select dropdown form field in React从 React 中的同一个选择下拉表单字段中获取多个值
【发布时间】:2020-07-09 17:02:55
【问题描述】:

我目前有一个带有选择下拉列表的 React Material 表单,我在其中映射一组对象并将名称字段显示为每个选项。我目前已将选项的 value 属性设置为对象的名称 (cpuParent.name)。但是,同一个对象也有一个瓦特字段(cpuParent.wattage),我也需要它的值。有没有办法可以从同一个下拉字段中获取对象的名称和功率?我在下面复制并粘贴了我的代码的相关 sn-ps - 该组件是一个类组件:

在类组件内,但在渲染方法之外:

constructor(props) {
    super(props);

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

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

渲染方法内部:

// 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>

【问题讨论】:

  • 如果您将值设置为索引,您可以在句柄更改中按索引访问整个对象,如 cpuParents[parseInt(event.target.value)] 或在选项标签中使用自定义属性并从 event.target 获取它

标签: javascript reactjs react-material


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您只需将选项值更改为整个对象即可获取整个对象

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

    现在标签将显示名称,但值将包含整个对象项。 您可以访问所需的任何值。

    您可以使用

    访问属性
      [name]: event.target.value['name']
      [name]: event.target.value['wattage']
    

    【讨论】:

      猜你喜欢
      • 2015-12-30
      • 1970-01-01
      • 2020-08-20
      • 2021-12-20
      • 2022-11-27
      • 2018-12-16
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      相关资源
      最近更新 更多