如何将分组的TextField值设置为状态?

时间:2018-12-24 02:35:00

标签: javascript reactjs material-ui

我正在建立一个带有React的网站。我创建了一个将Textfield分组的组件,我不知道如何将这些Textfield的值设置为state。 状态格式应为:state:{products:[{},{},{}]}

我试图创建一个按钮来插入新的Textfield组,并创建一个handleChange方法来捕获Textvalue, 但仍然停留在如何设置状态上。

export default class extends Component {
    state = {
        count: 0,

        products: []
    };

    handleAddClick = () => {
        this.setState(({count}) => ({
            count: count + 1
        }))
    };

    handleChange = e => {
        //this is where i stuck
    };

    render() {
        const {count} = this.state;
        let items = [];
        for (let i = 0; i <= count; i++) {
            items.push(
                <div key={i}>
                    <TextField
                        label="product"
                        margin="normal"
                        onChange={this.handleChange}
                    />
                    <TextField
                        label="color"
                        margin="normal"
                        onChange={this.handleChange}
                    />
                    <TextField
                        label="quantity"
                        margin="normal"
                        onChange={this.handleChange}
                    />
                    <TextField
                        label="price"
                        margin="normal"
                        onChange={this.handleChange}
                    />
                </div>
            )
        }
        return <Fragment>
            <Button onClick={this.handleAddClick}>
                <AddIcon/>
            </Button>
            {items}
        </Fragment>
    }
}

我意识到我必须使用一些id来标识不同的TextField组,但是要放在哪里以及如何在handleChange方法中获取它?

1 个答案:

答案 0 :(得分:1)

您的状态似乎是错误的,您需要再添加一个用于处理输入更改的键,将其称为product。因此,该产品将处理当前的文本框,一旦用户单击添加按钮,便可以将其添加到产品阵列。这个产品将成为一个物体。

state = {
  count: 0,
  product:{},
  products: [],
};

使用键传递文本字段值,以便您可以填充产品对象键,

<TextField value={this.state.product.product}
   label="product"
   type="text"
   margin="normal"
   onChange={(e) => { this.handleChange(e, 'product') }}
 />

并这样设置

handleChange = (e, type) => {
  this.setState({ 
    product: { 
      ...this.state.product, 
      [type]: e.target.value, 
    },
  });
};

当用户点击添加时,您可以将此产品推送到产品数组

handleAddClick = () => {
  this.setState({ 
    products: this.state.products.concat(this.state.product), 
    product: {}, 
  })
};

这是您的组件的外观:

将输入替换为TextField,将按钮替换为Button

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  state = {
    count: 0,
    product: {},
    products: [],
  };

  handleAddClick = () => {
    this.setState({ 
      products: this.state.products.concat(this.state.product), 
      product: { 
        product: "",
        color: "",
        quantity: "",
        price: "",
      }
    })
  };

  handleChange = (e, type) => {
    //this is where i stuck
    this.setState({ 
      product: { 
        ...this.state.product, [
          type]: e.target.value, 
      } 
    });
  };

  render() {
    console.log(this.state);
    const { count } = this.state;
    let items = [];
    for (let i = 0; i <= count; i++) {
      items.push(
        <div key={i}>
          <input value={this.state.product.product}
            label="product" type="text"
            margin="normal"
            onChange={(e) => { this.handleChange(e, 'product') }}
          />
          <input value={this.state.product.color}
            label="color"
            margin="normal"
            onChange={(e) => { this.handleChange(e, 'color') }}
          />
          <input value={this.state.product.quantity}
            label="quantity"
            margin="normal"
            onChange={(e) => { this.handleChange(e, 'quantity') }}
          />
          <input value={this.state.product.price}
            label="price"
            margin="normal"
            onChange={(e) => { this.handleChange(e, 'price') }}
          />
        </div>
      )
    }
    return (
      <div>
        <button onClick={this.handleAddClick}>
          add
        </button>
        {items}
      </div>
    )
  }
}



render(<App />, document.getElementById('root'));

编辑:

由于您要遍历产品并更改值,因此不再需要产品,我们将使用该产品作为产品的基本值,现在以下内容将发生更改,您需要获取每个产品的索引和默认情况下,我们将分配一个值

像这样

let product = { 
  product: "",
  color: "",
  quantity: "",
  price: "",
};
class App extends Component {
  state = {   
    products: [Object.assign({},product)],
  };

  handleAddClick = () => {  
    var newProduce = {
      product: "", 
      color: "", 
      quantity: "", 
      price: "", 
    }    
    this.setState({ 
      products: this.state.products.concat(newProduce),
    })
  };

  handleChange = (e, type, index) => {
    const copiedData = Object.assign({}, this.state);
    copiedData.products[index][type] = e.target.value;    
    this.setState(copiedData);
  };
  ...

Here is the demo