Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

react redux - Editable Form ReactJS

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, the manner your are changing the state is not good. You are setting the new state to have only a single attribute which is the name and value of the field which is modified.

Coming to how to print the value of the field you are modifying, you should do a console log in the handle change method.

That said, your code should look like:

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

For more insight on how to modify objects with assign method see: MDN doc on Object.assign()

If you want to print the current state on clicking the save button then add the onClick attribute to the button as shown in the code below:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...