将值设置为状态 React js

IT技术 reactjs state antd setstate
2021-05-23 02:14:36

我需要一点帮助。

我是新手,所以我一直在这里。我分享了一个sandbox盒子链接。包含一个表。如下

| 玩具 | 颜色可选 | 可用成本 |

现在一切正常。但我想保存表的数据如下

detail状态应该包含表的行值的列表,并且columnsValues应包含的复选框值Color AvailableCost Available

例子: this.state.detail喜欢

detail: [
  {
      toy   : ...
      color : ...
      cost  : ...
  }
  {
      toy   : ...
      color : ...
      cost  : ...
  }
  ...
  ...
  ...
]

this.state.columnsValues 喜欢

columnsValues: {
  color : boolean
  cost  : boolean
}

请任何专家帮助我。从过去的几个小时开始,我一直在挣扎。

谢谢你。

沙盒链接:https : //codesandbox.io/s/suspicious-microservice-qd3ku? file =/index.js

2个回答

只需粘贴此代码即可。

检查您的控制台,您将获得所需的输出。

import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Table, Checkbox, Input } from "antd";
import { PlusCircleOutlined, MinusCircleOutlined } from "@ant-design/icons";

const { Column } = Table;

class ToyTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [
        {
          key: 0,
          toy: "asdf",
          color: "black",
          cost: "23"
        }
      ],
      count: 0,
      colorSwitch: false,
      costSwitch: false,
      columnsValues: {
        color: true,
        cost: true
      },
      detail: []
    };
  }

  componentDidMount(){
    const count = this.state.dataSource.length;
    this.setState({
      count
    })
  }

  handleAdd = () => {
    const { dataSource } = this.state;
    let count = dataSource.length;
    const newData = {
      key: count,
      toy: "",
      color: "",
      cost: ""
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count
    });
  };
  handleDelete = key => {
    const dataSource = [...this.state.dataSource];
    this.setState({ dataSource: dataSource.filter(item => item.key !== key) });
  };
  onChangecolor = (e, record) => {
    let dataSource = this.state.dataSource;
    let key = record.key;
    dataSource[key].color = e.target.value;
    this.setState({
      dataSource
    });
  };
  onChangeCost = (e, record) => {
    let dataSource = this.state.dataSource;
    let key = record.key;
    dataSource[key].cost = e.target.value;
    this.setState({
      dataSource
    });
  };
  onChangeToy = (e, record) => {
    console.log("I am inside handleInputChange", e.target.value, record);
    let dataSource = this.state.dataSource;
    let key = record.key;
    dataSource[key].toy = e.target.value;
    this.setState({
      dataSource
    });
  };

  checkColor = e => {
    this.setState({ colorSwitch: e.target.checked });
  };

  checkCost = e => {
    this.setState({ costSwitch: e.target.checked });
  };
  render() {
    const { dataSource } = this.state;
    console.log(dataSource);

    return (
      <Table bordered pagination={false} dataSource={dataSource}>
        <Column
          title="Toy"
          align="center"
          key="toy"
          dataIndex="toy"
          render={(text, record) => (
            <Input
              component="input"
              className="ant-input"
              type="text"
              value={record.toy}
              onChange={e => this.onChangeToy(e, record)}
            />
          )}
        />

        <Column
          title={() => (
            <div className="row">
              Color Available
              <div className="col-md-5">
                <Checkbox size="small" onChange={this.checkColor} />
              </div>
            </div>
          )}
          align="center"
          dataIndex="color"
          render={(text, record) => (
            <Input
              disabled={!this.state.colorSwitch}
              value={record.color}
              onChange={e => this.onChangecolor(e, record)}
              component="input"
              className="ant-input"
              type="text"
            />
          )}
        />

        <Column
          title={() => (
            <div className="row">
              Cost Available
              <div className="col-md-5">
                <Checkbox size="small" onChange={this.checkCost} />
              </div>
            </div>
          )}
          align="center"
          dataIndex="color"
          render={(text, record) => (
            <Input
              disabled={!this.state.costSwitch}
              value={record.cost}
              onChange={e => this.onChangeCost(e, record)}
              component="input"
              className="ant-input"
              type="text"
            />
          )}
        />

        <Column
          render={(text, record) =>
            this.state.count !== 0 && record.key + 1 !== this.state.count ? (
              <MinusCircleOutlined
                onClick={() => this.handleDelete(record.key)}
              />
            ) : (
              <PlusCircleOutlined onClick={this.handleAdd} />
            )
          }
        />
      </Table>
    );
  }
}

ReactDOM.render(<ToyTable />, document.getElementById("container"));

这不是一个确切的答案,而只是一个总体方向 - 您需要一些东西state来捕获当前编辑的行内容的值,然后您可以将其添加到最终列表中。这是假设一旦提交,您就不想修改最终列表。

首先,有一个初始状态,用于存储正在编辑的当前行中的值

this.state = {
  currentData: {
    toy: '',
    color: '', 
    ..other props in the row
  }
  ...other state variables like dataSource etc
}

其次,当输入框中的值发生变化时,您必须更新currentData状态变量中的相应属性我看到你已经有了一个handleInputChange功能

例如,对于对应于 的输入框toy,你会做

 <input onChange={e => handleInputChange(e, 'toy')} ...other props />

在函数本身中,您将更新 currentData 状态变量,例如:

handleInputChange = (e, property) => {
  const data = this.state.currentData 
  data[property] = e.target.value
  this.setState({ currentData: data })
}

最后,当你在你的 中按下 add 时handleAddFunction,你想做两件事:

1) 使用currentDatain 状态,它一直在保存您的当前值并将它们推送到dataSourceordetails数组中

2) 恢复currentData到空白状态,准备跟踪下一行的更新。

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const newData = {
      key: count,
      ...this.state.newData,
    };
    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1, 
      currentData: {
        toy: '', 
        // other default values
      }
    });
  };