【问题标题】:Set value to state React js将值设置为状态 React js
【发布时间】:2020-10-01 05:15:03
【问题描述】:

我需要一点帮助。

我是新手,所以我卡在这里。我分享了一个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

【问题讨论】:

  • 看起来您已经将this.state.detail 中的所需内容保存为this.state.dataSource
  • 抱歉问了些愚蠢的问题。但是dataSource 没有我在表格行中输入的值。
  • 你没有任何初始状态,你为什么不设置呢?
  • 我说的是我们在行文本框中输入的值。我们从初始状态中得到了什么?
  • @Rich 我非常接近你的解决方案。

标签: reactjs state antd setstate


【解决方案1】:

只需粘贴此代码即可。

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

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

【讨论】:

  • 感谢您的解决方案。 :)
  • 很高兴有帮助:)。我必须这样做,因为我告诉过你我会在 2 小时内回复你??
  • 无论如何感谢您的关注。但是当我们删除一行(右侧的减号图标)然后添加另一行并尝试更改该行的值时,您的代码会出错。现在我正在检查相同的内容。如果可能,请检查一次。谢谢你。 :)
  • 抱歉回复晚了。但是我今天有点忙。所以,今天帮不了你。
  • 没关系。没问题。如果可能,请查看此link 一次。看起来很简单,但我还没有找到任何解决方案。谢谢。
【解决方案2】:

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

【讨论】:

  • 感谢您的帮助。我会查一下。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 2017-08-17
  • 2019-11-23
  • 2017-06-26
相关资源
最近更新 更多