通过迭代对象填充选择表单

时间:2017-12-01 03:36:17

标签: forms reactjs materialize

尝试使用我作为道具传递给我的组件的对象填充选择表单。该对象如下所示:{24: {14: 64.99, 20: 89.99, 26: 114.99}, 30: {14: 74.99, 20: 99.99, 26: 124.99}我试图将2430作为我的表单中的值进行隔离。这是相关的代码:

import React, { Component } from 'react';
import { Row, Input } from 'react-materialize';

class HeightPicker extends Component {
  constructor(props){
    super(props);
    this.state = {
      height: '',
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
      this.setState({height: e.target.value});
    }

  displayHeights(){
    let prices = this.props.prices;
    let height;
    let heights = [];
    console.log(prices);
    for (height in prices) {
      heights.push(height)
    };
    console.log(heights);
    heights.forEach(function(h) {
      return(<option value={h}>{h}</option>);
    });
  }

  render() {
    return(
      <div>
        <Row>
           <Input l={12} value={this.state.height} onChange={this.handleChange} type='select' label="Height">
             {this.displayHeights()}
           </Input>
        </Row>
      </div>
    )
  };
};

export default HeightPicker;

如上所述,它返回一个空白表格。如果我将选项硬编码到我的渲染函数中它是有效的,因此我假设我的问题是通过我的displayHeights函数产生的。但是我之前也遇到过React Materialize和React I版本运行的问题 - 不得不将版本从16.0.0降级到15.6.2 - 所以我想知道它是否与此相关。任何帮助,将不胜感激。感谢。

3 个答案:

答案 0 :(得分:1)

map方法

中使用forEach代替displayHeights

forEach方法对数组或集合的每个元素执行一些操作,但不返回修改后的元素,map方法在一些操作后返回修改后的元素

您的实施有两个问题

  1. 您使用的forEach不会返回修改后的元素
  2. 您没有return包含选项的数组,在您的情况下,heights
  3. 修改后的代码块将是

    return heights.map(function(h) {
      return(<option value={h}>{h}</option>);
    });
    

答案 1 :(得分:0)

这应该是您的displayHeights功能。这是WORKING DEMO

您需要在函数中返回数组,并且map也是您应该使用的。

displayHeights(){
    let prices = this.props.prices;
    let height;
    let heights = [];
    console.log(prices);
    for (height in prices) {
      heights.push(height)
    };
    console.log(heights);
    return heights.map(function(h, i) {
      return(<option key={i} value={h}>{h}</option>);
    });
  }

使用forEach

let heightsJSX = [];
heights.forEach(function(h, i) {
  heightsJSX.push(<option key={i} {value={h}>{h}</option>));
});

return heights;

答案 2 :(得分:0)

为了效率,为什么不只是map超过键。这是一个单行。

displayHeight() {

    return Object.keys(this.props.prices).map(key => <option key={key} value={key}>{key}</option>);
}