如何将输入的数据从子级获取到我的父级组件中?

时间:2018-06-23 12:06:57

标签: reactjs components parent-child state react-props

我正在做这个应用程序,我们可以在列表内添加列表和输入字段,并且应该将数量加起来并显示在所有列表的末尾,但是我无法将输入传递给父母。 / p>

我的代码: 父级-列表

import React from 'react';
import styled from 'styled-components';
import InputFields from './InputFields';

const Container = styled.div `
  display: flex;
  flex-direction: row;
  justify-content: space-between;
`;

class ShoppingList extends React.Component {

  state = {
    inputFields: [],
    value: 0
  }

  AddInputField = () => {
    const inputFields = this.state.inputFields.concat(InputFields);
    this.setState({
      inputFields
    })
    console.log(this.state.inputFields);
  }

  onUpdate = (val) => {
    this.setState({
      value: val
    })
    console.log(this.state.inputFields[0]);
  }

  render() {
    const inputFields = this.state.inputFields.map((Element, index) => {
      return <Element
        key={index}
        index={index}
        value={this.onUpdate}
             />
    });

    return (
      <div>
        <Container>
          <select>
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="mercedes">Mercedes</option>
          </select>
          <button onClick={this.AddInputField}>Add expense</button>
        </Container>
        <InputFields value={this.onUpdate}/>
        {inputFields}
        <Container>
          <label>Total:</label>
          <label>{this.state.value+'€'}</label>
        </Container>
      </div>
    );
  }
}

export default ShoppingList;

孩子-输入字段

import React from 'react';
import styled from 'styled-components';

const Container = styled.div `
  display: flex;
  flex-direction: row;
  justify-content: space-between;
`;

class InputFields extends React.Component {
  state = {
    value: ''
  }


  handleChange = (event) => {
    console.log(event.target.value);
    this.setState({
      value: event.target.value
    })

    this.props.value(event.target.value);
  }

  render() {
    return (
      <Container>
        <input></input>
        <input type="number" value={this.state.value} onChange={event => this.handleChange(event)}></input>
      </Container>
    );
  }
}

export default InputFields;

如何传递每个添加的输入字段中的输入值并将它们加起来,以便列表可以显示列表中所有项目的价格?

编辑/更新-我得到了绑定,如果我添加2个或更多输入字段,它将明显覆盖状态,但是如何保留所有输入中的值并将它们相加呢? 我更新了代码

0 个答案:

没有答案