动态地对用户输入反应js

时间:2017-03-11 09:59:53

标签: reactjs

import React, { Component } from 'react';
import { Link } from 'react-router'
import { Dropdown, DropdownMenu, DropdownItem, Progress } from 'reactstrap';

class Modals extends Component {
  constructor(){
    super();
    alert("start3e");
fetch("http://api-env.bt2qjip33m.ap-south-1.elasticbeanstalk.com/api/v1/beacons" ,
 {
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
    'Authorization' : 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGMyOTdiOWQzZWM4NjY4MDMwNDBlNjgiLCJlbWFpbCI6ImtrQGxpdGlmZXIuY29tIiwiZmlyc3ROYW1lIjoiS2lzaGxheSIsImxhc3ROYW1lIjoiS2lzaG9yZSIsImlhdCI6MTQ4OTE0NzgzM30.nHW5w3SSov8ySziblmw2VNlGI3CsZFR-v41Jeg9uBVs'
},
body: JSON.stringify({
    name: "beacon name 123",
    description: "beacon description here for beacon",
    uuid: "mnvijefnvj4356vrev",
    major: "7",
    minor: "9",
    manufacturer: "m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24",
    beaconType: "type9",
    location: "main gate8",
    floor: "ist",
    zone: "58c29c06d3ec866803040e6e"
})
}).then(function(response){
  if(response.ok) {
      console.log(response)
    return response;
  }
  throw new Error('Network response was not ok.');
}).then(function(data) { 
  console.log(data);
})
.catch(function(error) {
  console.log('There has been a problem with your fetch operation: ' + error);
});
}
  render() {
    return (<div><div>
          <div className="animated fadeIn">
            <br /><div className="card" style={{ width: 57 + '%' }}>
              <div className="card-header">
                 Beacon Settings
              </div>
              <div className="card-block">
                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="icon-user"></i></span>
                  <input type="text" className="form-control" placeholder="UUID" />
                </div>

                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
                  <input type="text" className="form-control" placeholder="Major Number"/>
                </div>

                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
                  <input type="text" className="form-control" placeholder="Minor Number"/>
                </div>

                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
                  <input type="text" className="form-control" placeholder="Manufacturer Number"/>
                </div><center>
                <Link to={'/components/tabs'} style={{ width: 27 + '%' }} className="nav-link btn btn-block btn-success" activeClassName="active">Save</Link>

<Link to={'/components/tabs'} style={{ width: 27 + '%' }} className="nav-link btn btn-block btn-success" activeClassName="active">Advance Settings</Link>
</center>

            </div>
          </div>
</div></div>
      </div>
      
        
      
    )
  }
}

export default Modals;

我只想从屏幕上获取用户输入。 该怎么做? 之后,我将使用post request在服务器上发布这些值,这是正常工作。 我只想在屏幕上的字段中使用用户值,并将这些值动态发送到服务器

2 个答案:

答案 0 :(得分:0)

通常我使用redux-form,这样可以很容易地在表单提交上收集值。

如果您没有使用它(我没有看到您这样做),您可以执行以下操作之一:

  1. 将状态引入整个组件,并将onChange处理程序引入更新状态的所有输入
  2. 将ref设置为每个输入并获取提交处理函数中的值。
  3. 如果您没有需要验证表格的情况,那么您不需要州和参考可以帮助您。

    所以完整的代码示例将是:

    import React, {Component} from 'react';
    import {Link} from 'react-router'
    import {Dropdown, DropdownMenu, DropdownItem, Progress} from 'reactstrap';
    
    class Modals extends Component {
      constructor() {
        super();
    
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      handleSubmit() {
        const uuid = this.uuid.value;
        const manufacturer = this.manufacturerNumber.value;
        const minor = this.minorNumber.value;
        const major = this.majorNumber.value;
    
        fetch("http://api-env.bt2qjip33m.ap-south-1.elasticbeanstalk.com/api/v1/beacons" ,
         {
          method: 'post',
          headers: {
            'Content-Type': 'application/json',
            'Authorization' : 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGMyOTdiOWQzZWM4NjY4MDMwNDBlNjgiLCJlbWFpbCI6ImtrQGxpdGlmZXIuY29tIiwiZmlyc3ROYW1lIjoiS2lzaGxheSIsImxhc3ROYW1lIjoiS2lzaG9yZSIsImlhdCI6MTQ4OTE0NzgzM30.nHW5w3SSov8ySziblmw2VNlGI3CsZFR-v41Jeg9uBVs'
        },
        body: JSON.stringify({
            name: "beacon name 123",
            description: "beacon description here for beacon",
            uuid: uuid,
            major: major,
            minor: minor,
            manufacturer: manufacturer,
            beaconType: "type9",
            location: "main gate8",
            floor: "ist",
            zone: "58c29c06d3ec866803040e6e"
        })
        }).then(function(response){
          if(response.ok) {
              console.log(response)
            return response;
          }
          throw new Error('Network response was not ok.');
        }).then(function(data) {
          console.log(data);
        })
        .catch(function(error) {
          console.log('There has been a problem with your fetch operation: ' + error);
        });
      }
    
      render() {
        return (
          <form onSubmit={this.handleSubmit}>
            <div className="animated fadeIn">
              <br/>
              <div className="card" style={{
                width: 57 + '%'
              }}>
                <div className="card-header">
                  Beacon Settings
                </div>
                <div className="card-block">
                  <div className="input-group mb-1">
                    <span className="input-group-addon">
                      <i className="icon-user" />
                    </span>
                    <input
                      ref={ref => (this.uuid = ref)}
                      type="text"
                      className="form-control"
                      placeholder="UUID"
                    />
                  </div>
    
                  <div className="input-group mb-1">
                    <span className="input-group-addon">
                      <i className="fa fa-align-justify" />
                    </span>
                    <input
                      ref={ref => (this.majorNumber = ref)}
                      type="text"
                      className="form-control"
                      placeholder="Major Number"
                    />
                  </div>
    
                  <div className="input-group mb-1">
                    <span className="input-group-addon">
                      <i className="fa fa-align-justify" />
                    </span>
                    <input
                      ref={ref => (this.minorNumber = ref)}
                      type="text"
                      className="form-control"
                      placeholder="Minor Number"
                    />
                  </div>
    
                  <div className="input-group mb-1">
                    <span className="input-group-addon">
                      <i className="fa fa-align-justify" />
                    </span>
                    <input
                      ref={ref => (this.manufacturerNumber = ref)}
                      type="text"
                      className="form-control"
                      placeholder="Manufacturer Number"
                    />
                  </div>
    
                  <center>
                    <Button type="submit" color="primary">
                      Click me to send values to the api!
                    </Button>
                    <Link to={'/components/tabs'}
                      className="nav-link btn btn-block btn-success"
                      activeClassName="active"
                      style={{
                        width: 27 + '%'
                      }}
                    >
                      Save
                    </Link>
    
                    <Link to={'/components/tabs'}
                      className="nav-link btn btn-block btn-success"
                      activeClassName="active"
                      style={{
                        width: 27 + '%'
                      }}
                    >
                      Advanced Settings
                    </Link>
                  </center>
                </div>
              </div>
            </div>
          </form>
        )
      }
    }
    
    export default Modals;
    

    我没有对它进行过测试,但它可以帮助您了解该怎么做。 通常我不使用refs来获取输入的值,因为我在所有最近的项目中都使用了redux-form。一定要检查一下。

答案 1 :(得分:0)

&#13;
&#13;
import React, { Component } from 'react';
import { Link } from 'react-router'
import { Dropdown, DropdownMenu, DropdownItem, Progress } from 'reactstrap';

class Modals extends Component {
  constructor(props){
    super(props);
    this.state = {inputuuid: '',
    inputmajor: '' ,
    inputminor: '' ,
    inputmanufacturer: ''};
    this.handleUuid = this.handleUuid.bind(this);
    this.handleMajor = this.handleMajor.bind(this);
    this.handleMinor = this.handleMinor.bind(this);
    this.handleManufacturer = this.handleManufacturer.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    alert("started");
fetch("http://api-env.bt2qjip33m.ap-south-1.elasticbeanstalk.com/api/v1/beacons" ,
 {
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
    'Authorization' : 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1OGMyOTdiOWQzZWM4NjY4MDMwNDBlNjgiLCJlbWFpbCI6ImtrQGxpdGlmZXIuY29tIiwiZmlyc3ROYW1lIjoiS2lzaGxheSIsImxhc3ROYW1lIjoiS2lzaG9yZSIsImlhdCI6MTQ4OTE0NzgzM30.nHW5w3SSov8ySziblmw2VNlGI3CsZFR-v41Jeg9uBVs'
},
body: JSON.stringify({
    name: "beacon name 1234",
    description: "beacon description here for beacon",
    uuid: this.state.inputuuid,
    major: "{this.state.inputmajor}",
    minor: "{this.state.inputminor}",
    manufacturer: "{this.state.inputmanufacturer}",
    beaconType: "type9",
    location: "main gate8",
    floor: "ist",
    zone: "58c29c06d3ec866803040e6e"
})
}).then(function(response){
  if(response.ok) {
      console.log(response)
    return response;
  }
  throw new Error('Network response was not ok.');
}).then(function(data) { 
  console.log(data);
})
.catch(function(error) {
  console.log('There has been a problem with your fetch operation: ' + error);
});
}

handleUuid(event) {

    this.setState({inputuuid: event.target.value});
  }
  handleMajor(event){
    this.setState({inputmajor: event.target.value});
  }
  handleMinor(event){
    this.setState({inputminor: event.target.value});
  }
  handleManufacturer(event){
        this.setState({inputmanufacturer: event.target.value});
  }
handleSubmit(event) {

    alert('Submitted: ' + this.state.inputuuid + this.state.inputmajor + this.state.inputminor + this.state.inputmanufacturer);
    event.preventDefault();
  }

  render() {
    const uuid= this.state.inputuuid;
    return (<div><div>
          <div className="animated fadeIn">
            <br /><div className="card" style={{ width: 57 + '%' }}>
              <div className="card-header">
                 Beacon Settings
              </div>
              <div className="card-block">
                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="icon-user"></i></span>
                  <input type="text"  className="form-control" value={this.state.inputuuid} onChange={this.handleUuid} placeholder="UUID" />
                </div>

                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
                  <input type="text" className="form-control" value={this.state.inputmajor} onChange={this.handleMajor} placeholder="Major Number"/>
                </div>

                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
                  <input type="text" className="form-control" value={this.state.inputminor} onChange={this.handleMinor} placeholder="Minor Number"/>
                </div>

                <div className="input-group mb-1">
                  <span className="input-group-addon"><i className="fa fa-align-justify"></i></span>
                  <input type="text" className="form-control" value={this.state.inputmanufacturer} onChange={this.handleManufacturer} placeholder="Manufacturer Number"/>
                </div><center>
                <Link to={'/components/tabs'} style={{ width: 27 + '%' }} className="nav-link btn btn-block btn-success"  onClick={this.handleSubmit} activeClassName="active">Save</Link>

<Link to={'/components/tabs'} style={{ width: 27 + '%' }} className="nav-link btn btn-block btn-success" activeClassName="active">Advance Settings</Link>
</center>

            </div>
          </div>
</div></div>
      </div>
      
        
      
    )
  }
}

export default Modals;
&#13;
&#13;
&#13;

这是答案,因为我在不同的输入上应用了不同的状态