将值设置为状态 React js [英] Set value to state React js

查看:33
本文介绍了将值设置为状态 React js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助.

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

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

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

detail 状态应包含表的行值列表,columnsValues 应包含 Color Available 和 <代码>可用成本

示例:this.state.detail 喜欢

详情:[{玩具   : ...颜色 : ...成本  : ...}{玩具   : ...颜色 : ...成本  : ...}.........]

this.state.columnsValues 就像

columnsValues: {颜色:布尔值成本:布尔值}

任何专家都请帮助我.过去几个小时我一直在挣扎.

谢谢.

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

解决方案

只需粘贴此代码即可.

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

从react"导入React;从react-dom"导入 ReactDOM;导入antd/dist/antd.css";导入./index.css";import { Table, Checkbox, Input } from "antd";从@ant-design/icons"导入 { PlusCircleOutlined, MinusCircleOutlined };const { 列} = 表;类 ToyTable 扩展了 React.Component {构造函数(道具){超级(道具);this.state = {数据源: [{关键:0,玩具:asdf",颜色:黑色",费用:23"}],计数:0,颜色开关:假,成本开关:假,列值:{颜色:真实,费用:真实},细节: []};}componentDidMount(){const count = this.state.dataSource.length;this.setState({数数})}handleAdd = () =>{const { 数据源 } = this.state;让计数 = dataSource.length;const newData = {关键:计数,玩具: "",颜色: "",成本: ""};this.setState({数据源:[...数据源,新数据],数数});};handleDelete = 键 =>{const dataSource = [...this.state.dataSource];this.setState({ dataSource: dataSource.filter(item => item.key !== key) });};onChangecolor = (e, record) =>{让数据源 = this.state.dataSource;让键 = record.key;数据源[key].color = e.target.value;this.setState({数据源});};onChangeCost = (e, record) =>{让数据源 = this.state.dataSource;让键 = record.key;数据源[key].cost = e.target.value;this.setState({数据源});};onChangeToy = (e, record) =>{console.log("我在 handleInputChange", e.target.value, record);让数据源 = this.state.dataSource;让键 = record.key;数据源[key].toy = e.target.value;this.setState({数据源});};checkColor = e =>{this.setState({ colorSwitch: e.target.checked });};checkCost = e =>{this.setState({ costSwitch: e.target.checked });};使成为() {const { 数据源 } = this.state;控制台日志(数据源);返回 (<表格边框分页={false} dataSource={dataSource}><列标题=玩具"对齐=中心"键=玩具"数据索引=玩具"渲染={(文本,记录)=>(<输入组件=输入"类名=蚂蚁输入"类型=文本"价值={记录.玩具}onChange={e =>this.onChangeToy(e, record)}/>)}/><列标题={() =>(<div className="row">颜色可选<div className="col-md-5"><Checkbox size="small" onChange={this.checkColor}/>

)}对齐=中心"数据索引=颜色"渲染={(文本,记录)=>(<输入禁用={!this.state.colorSwitch}值={记录.颜色}onChange={e =>this.onChangecolor(e, record)}组件=输入"类名=蚂蚁输入"类型=文本"/>)}/><列标题={() =>(<div className="row">可用成本<div className="col-md-5"><Checkbox size="small" onChange={this.checkCost}/>

)}对齐=中心"数据索引=颜色"渲染={(文本,记录)=>(<输入禁用={!this.state.costSwitch}价值={记录.成本}onChange={e =>this.onChangeCost(e, record)}组件=输入"类名=蚂蚁输入"类型=文本"/>)}/><列渲染={(文本,记录)=>this.state.count !== 0 &&record.key + 1 !== this.state.count ?(<减号圆轮廓onClick={() =>this.handleDelete(record.key)}/>) : (<PlusCircleOutlined onClick={this.handleAdd}/>)}/></表>);}}ReactDOM.render(, document.getElementById("container"));

I need a bit of help.

I am new to react, so I have stuck here. I have shared a sandbox box link. That Contains a Table. as below

| Toy | Color Available | Cost Available |

Now everything works perfectly. But I want to save the data of the table as below

The detail state should contain a list of row values of the table and the columnsValues should contain the checkbox value of Color Available and Cost Available

Example: this.state.detail like

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

this.state.columnsValues like

columnsValues: {
  color : boolean
  cost  : boolean
}

Any experts please help me out. I am struggling from past few hours.

Thank you.

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

解决方案

just paste this code it is working .

check your console you'll get your desired output .

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

这篇关于将值设置为状态 React js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆