将值设置为状态 React js

Set value to state React js

我需要一点帮助。

我是react新手,所以一直卡在这里。我分享了一个 sandbox 盒子 link。包含 Table。如下

|玩具 |颜色可选 |可用费用 |

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

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

示例: this.state.detail 喜欢

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

this.state.columnsValues 喜欢

columnsValues: {
  color : boolean
  cost  : boolean
}

请哪位高手帮帮我。过去几个小时我一直在挣扎。

谢谢。

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

这不是一个确切的答案,只是一个大致的方向 - 您需要 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 })
}

最后,当您按添加时,在您的 handleAddFunction 中,您想做两件事:

1) 在状态中使用 currentData,它一直在保存您的当前值并将它们推入 dataSourcedetails 数组

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
      }
    });
  };

只需粘贴此代码即可。

检查你的控制台你会得到你想要的输出。

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"));