可编辑的表格ReactJS

时间:2017-03-31 17:21:42

标签: reactjs react-redux

import React, { Component } from 'react';
let _ = require('lodash');

import {bindActionCreators} from "redux";
import {connect} from 'react-redux';

import {fetchedBeaconsEdit} from '../../actions/';
import {editBeacon} from '../../actions/index';

// TODO - come up with a decent name

class InfoRow extends Component {

    render() {
        return (

            <tr>
                <td>
              { this.props.beacon === "name" 
                || this.props.beacon === "major" 
                || this.props.beacon === "minor" 
                || this.props.beacon === "beaconType" ?
                  <span>{this.props.beacon}<span className="font-css top">*</span></span>:
                  <span>{this.props.beacon}</span>
              }

                </td>
                <td>

                { this.props.beacon !== "beaconType" && 
                  this.props.beacon !== "uuid" && 
                  this.props.beacon !== "status" && 
                  this.props.beacon !== "store"&&
                  this.props.beacon !== "group" ?
                <div>
                    <input type="text"
                       className="form-control"
                       defaultValue={this.props.beaconValue}
                       name={this.props.beaconValue}
                       onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}
                    /></div>:

                    this.props.beacon === "uuid" && this.props.beacon === "status" && this.props.beacon=== "store"?
                  <span></span>:

                    this.props.beacon === "beaconType"?

                    <select defaultValue={this.props.beaconValue} name={this.props.beaconValue} className="form-control" onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}>
                      
                      <option name="ibeacon">IBEACON</option>
                      <option name="eddystone">EDDYSTONE</option>
                    </select>:this.props.beaconValue

                    

                }



                </td>
            </tr>
        )
    }
}

class BeaconEdit extends Component {

  constructor(props){
    super(props);
    this.state = {
            
        };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  handleInputChange(beacon, value) {

        this.setState({
            [beacon]: value
        });
    }

 handleClick = () =>{
       Object.keys(this.props.ebcn).map((key)=> {
        if (this.state[key] !== undefined) {
          this.props.editBeaconGroup[key]=this.state[key];
        }
            
       })
        this.props.handleSubmitProp(this.props.editBeaconGroup);
  }
 
    render() {

        const rows = [];
        let a = this.props.ebcn;

        

       Object.keys(this.props.ebcn).map((keyName, keyIndex) =>{

          if (keyName === "store" || keyName === "group") {
            return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].name.toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
          }else{
            return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
       }
       });

        return (


            <div className="col-md-6">
                <div className="">

                  <table className="table table-clear">
                    <tbody>
              
                    {rows}
                    
                    </tbody>
                  </table>
                 </div>
                 <div className="px-1" >
                        <button className="btn btn-sm btn-info btn-size btn-block" onClick={this.handleClick}>Save</button>
                 </div>
          </div>

        )

    }


}

class BeaconDetailEditComponent extends Component {
  
  constructor(props){
    super(props);
    this.state = {
        editbeacons: {}
        };
        this.handleSubmit = this.handleSubmit.bind(this);

        this.validateName = this.validateName.bind(this);
        this.validateMajor = this.validateMajor.bind(this);
        this.validateMinor = this.validateMinor.bind(this);
    }

    validateMinor = (minor) => {
      var re = /^[0-9]+$/;
      return re.test(minor);
    }

    validateMajor = (major) => {
      var re = /^[0-9]+$/;
      return re.test(major);
    }

    validateName = (name) => { 
      var re = /^[A-Za-z ]+$/;
      return re.test(name); 
    };


  handleSubmit (beaconedited) {

    console.log(beaconedited.name);

    if (!this.validateName(beaconedited.name)) { 
              alert('Name can not be an integer')  
          }

    else if (!this.validateMajor(beaconedited.major)) { 
              alert('Major number can only be an integer')  
          }

        else if (beaconedited.major.length > 5) {
          alert('Major number can not exceed 5 digits')
        }

        else if (!this.validateMinor(beaconedited.minor)) { 
              alert('Minor number can only be an integer')  
          }

        else if (beaconedited.major > 65535) {
          alert('Major number can not exceed the limit of 65535')
        }

        else if (beaconedited.minor > 65535) {
          alert('Minor number can not exceed the limit of 65535')
        }

    else {

      this.props.editBeacon(beaconedited, this.props.location.query.id);
    
  }
    }

  componentWillMount = () => {
        this.props.fetchedBeaconsEdit(this.props.location.query.id);  
    };

  
  render() {
    
    return (
        <div className="container px-3 mr-3">
            <div>
              <div className="col-md-6 col-md-offset-3"><h1>Edit Beacon Information</h1></div>
            </div>
            <br/>
            <br/>
                { this.props.ebcn != null?
            <div>
                <BeaconEdit ebcn={this.props.ebcn} handleSubmitProp={this.handleSubmit} editBeaconGroup={this.state.editbeacons}/>
            </div> :
                    <center><img className="gif-size" src={'img/avatars/default.gif'} alt="Loading"/></center>

            }
        </div>
    )
  }
}

function mapStateToProps(state) {
    return {
        eBeacon: state.eBeacon,
        ebcn: state.beacons
    }

}


function matchDispatchToProps(dispatch){
    return bindActionCreators({editBeacon: editBeacon, fetchedBeaconsEdit: fetchedBeaconsEdit}, dispatch);
}

export default connect(mapStateToProps, matchDispatchToProps)(BeaconDetailEditComponent);

This is the output I'm getting right now

enter image description here

我提供了代码段 我在做什么 我从服务器获取了值并显示在字段中,我将此页面设置为可编辑形式 我想要做的是现在采取用户更改或更改的值,并在控制台中打印它们。 我已经应用了handleInputChange并在更改时显示更改的值,但我想在按钮单击时在控制台中看到这些值 怎么做?

2 个答案:

答案 0 :(得分:1)

首先,你改变国家的方式并不好。您正在将新状态设置为仅具有单个属性,该属性是已修改字段的名称和值。

如何打印您正在修改的字段的值,您应该在句柄更改方法中执行控制台日志。

那就是说,你的代码应该是这样的:

handleInputChange(event) {

    //const {name, value} = event.target;
    //const oldState = this.state;
    //const newState = Object.assign({},oldState,{[name]:value});
    //this.setState(newState);

    this.setState({
        [event.target.name]: event.target.value
    });

    //printing the input name and value as it is being modified.
    console.log(name + ":" + value);

    //if you want to see the value of the current state uncomment the line below
    //console.log("State=" + JSON.stringify(newState));

}

printState = () => {
  console.log("State="+JSON.stringify(this.state));
}

有关如何使用assign方法修改对象的更多信息,请参阅:MDN doc on Object.assign()

如果要在单击“保存”按钮时打印当前状态,请将onClick属性添加到按钮,如下面的代码所示:

<button value="Save" onClick={this.printState}/>

答案 1 :(得分:1)

将InfoRow更改为

class InfoRow extends Component {

    render() {
        return (

            <tr>
                <td>
                  {this.props.beacon}
                </td>
                <td>
                <input type="text"
                   className="form-control"
                   defaultValue={this.props.beaconValue}
                   value={this.props.name}
                   name={this.props.beaconValue}
                   onChange={(e) =>this.props.handleInputChangeProp(e.target.value)}
                />
                </td>
            </tr>
        )
    }
}

并渲染到

Object.keys(this.props.ebcn).map((keyName, keyIndex) =>{

          return rows.push(<InfoRow beacon={keyName} beaconValue={a[keyName].toString()} name={this.state[keyName]} key={keyIndex} handleInputChangeProp={(inp) =>this.handleInputChange(keyName, inp)}/>);
       });

handleInputChange(beacon, value) {

        this.setState({
            [beacon]: value
        });
    }

和handleClick to

 handleClick = () =>{
       Object.keys(this.props.ebcn).map((key)=> {
            console.log(this.state[key]);
       }))
  }