Get form data in Reactjs

2019-01-07 03:26发布

I have a simple form in my render function, like so:

render : function() {
      return (
        <form>
          <input type="text" name="email" placeholder="Email" />
          <input type="password" name="password" placeholder="Password" />
          <button type="button" onClick={this.handleLogin}>Login</button>
        </form>
      );
    },
handleLogin: function() {
   //How to access email and password here ?
}

What should I write in my handleLogin: function() { ... } to access Email and Password fields ?

15条回答
Rolldiameter
2楼-- · 2019-01-07 03:53
 onChange(event){
     console.log(event.target.value);
  }
  handleSubmit(event){ 
    event.preventDefault();
    const formData = {};
      for (const data in this.refs) {
        formData[data] = this.refs[data].value;
      }
    console.log(formData);
  }



 <form onSubmit={this.handleSubmit.bind(this)}>
  <input type="text" ref="username" onChange={this.onChange} className="form-control"/>
  <input type="text" ref="password" onChange={this.onChange} className="form-control"/>
  <button type="submit" className="btn-danger btn-sm">Search</button>
 </form>

Output image attached here

查看更多
贪生不怕死
3楼-- · 2019-01-07 03:54

An alternative approach is to use the ref attribute and reference the values with this.refs. Here is a simple example:

render: function() {
    return (<form onSubmit={this.submitForm}>
        <input ref="theInput" />
    </form>);
},
submitForm: function(e) {
    e.preventDefault();
    alert(React.findDOMNode(this.refs.theInput).value);
}

More info can be found in the React docs: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

For a lot of the reasons described in How do I use radio buttons in React? this approach isn't always the best, but it does present a useful alternative in some simple cases.

查看更多
The star\"
4楼-- · 2019-01-07 03:55

Also, this can be used too.

handleChange: function(state,e) {
  this.setState({[state]: e.target.value});
},
render : function() {
  return (
    <form>
      <input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleChange.bind(this, 'email')} />
      <input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handleChange.bind(this, 'password')}/>
      <button type="button" onClick={this.handleLogin}>Login</button>
    </form>
  );
},
handleLogin: function() {
  console.log("EMail: ", this.state.email);
  console.log("Password: ", this.state.password);
}
查看更多
登录 后发表回答