将具有2个属性的多个对象推入数组

时间:2018-07-28 18:48:14

标签: javascript reactjs

我正在尝试为医生创建处方表格, 必须添加具有剂量说明的新药,因此每次医生单击添加另一个时,我都会动态添加两个输入。但是我无法处理将两个输入的对象都推入数组的更改 我正在尝试得到这样的东西:

dosis: [
    {
        name: medicine1,
        instructions: every 6 hrs
    },
    {
        name: medicine2,
        instructions: every 8 hrs
    }
]

这是我的父组件,其中添加了子组件:

<ParentComponent addChild={this.onAddChild}>
    <div className="form-group col-md-6 align-middle">                                        
        <label>Medicine name:</label>
        <Search
             data={ this.state.data }
             onChange={ this.handleChangeComponent.bind(this) }
             placeholder="Search for a string..."
             class="search-class  upperinput"
             searchKey="name"
             value={this.state.name}
             ref="medicine"

         />
    </div>
    <div className="form-group col-md-6 align-middle">
        <label for="medicamento-search">Indicaciones y Duración del Tx:</label>                                                                      
        <input type="text" class="form-control" name="instructions" ref="instructions" onChange={this.handleChange} value={this.state.instructions} placeholder="Instructions.."/>
                                </div>
    {children}
</ParentComponent>  

搜索组件具有自动完成搜索栏,因此我可以像这样处理更改:

handleChangeComponent(e) {
    this.setState({ name: e });
  }

指令输入的是常规输入,因此处理程序为:

 handleChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }

这也是我将孩子添加到parentComponent的方式

   onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
    render() {

    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<MedicineSearch data={this.state.data} searchKey="name" key={i} number={i} value={this.state.name} onChange={ this.handleChangeComponent.bind(this) }/>);
    };
    return (... My HTML )


const ParentComponent = props => (

    <div className="col-md-12 row" id="children-pane">
        {props.children}
    </div>
);

这里是CodeSandbox链接: https://codesandbox.io/s/zwr101okom

1 个答案:

答案 0 :(得分:0)

您可以将dosis置于您的状态,然后在单击添加按钮时添加一个具有nameinstructions属性的新对象,最后在渲染器中循环此数组方法。

示例

class Home extends React.Component {
  state = {
    data: [{ name: "Adderall" }, { name: "Xanax" }],
    loading: false,
    dosis: [
      {
        name: "test medicine",
        instructions: "every 6 hrs"
      }
    ]
  };

  handleChange = (e, index) => {
    const { name, value } = e.target;

    this.setState(prevState => {
      const dosis = [...prevState.dosis];
      dosis[index] = { ...dosis[index], [name]: value };
      return { dosis };
    });
  };

  onAddChild = () => {
    this.setState(prevState => {
      return {
        dosis: [
          ...prevState.dosis,
          {
            name: "new medicine",
            instructions: "some instruction"
          }
        ]
      };
    });
  };

  render() {
    return (
      <div>
        {this.state.dosis.map((element, i) => (
          <div>
            <div> Medicine Name </div>
            <input
              value={element.name}
              name="name"
              onChange={e => this.handleChange(e, i)}
            />
            <div> Instructions </div>
            <input
              value={element.instructions}
              name="instructions"
              onChange={e => this.handleChange(e, i)}
            />
          </div>
        ))}
        <div>
          <button onClick={this.onAddChild}>Add Dosis</button>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Home />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>