我在渲染函数中有一个简单的表单,如下所示:

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 ?
}

我应该在我的handleLogin: function(){…}访问电子邮件和密码字段?


当前回答

像这样给你的输入参考

<input type="text" name="email" placeholder="Email" ref="email" />
<input type="password" name="password" placeholder="Password" ref="password" />

然后你可以像soo一样在你的handleLogin中访问它

handleLogin: function(e) {
   e.preventDefault();
    console.log(this.refs.email.value)
    console.log(this.refs.password.value)
}

其他回答

有几种方法可以做到这一点:

1)通过索引从数组的表单元素中获取值

handleSubmit = (event) => {
  event.preventDefault();
  console.log(event.target[0].value)
}

2)在html中使用name属性

handleSubmit = (event) => {
  event.preventDefault();
  console.log(event.target.elements.username.value) // from elements property
  console.log(event.target.username.value)          // or directly
}

<input type="text" name="username"/>

3)使用裁判

handleSubmit = (event) => {
  console.log(this.inputNode.value)
}

<input type="text" name="username" ref={node => (this.inputNode = node)}/>

完整的示例

class NameForm extends React.Component {
  handleSubmit = (event) => {
    event.preventDefault()
    console.log(event.target[0].value)
    console.log(event.target.elements.username.value)
    console.log(event.target.username.value)
    console.log(this.inputNode.value)
  }
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input
            type="text"
            name="username"
            ref={node => (this.inputNode = node)}
          />
        </label>
        <button type="submit">Submit</button>
      </form>
    )
  }
}

使用输入中的change事件来更新组件的状态,并在handllogin中访问它:

handleEmailChange: function(e) {
   this.setState({email: e.target.value});
},
handlePasswordChange: function(e) {
   this.setState({password: e.target.value});
},
render : function() {
      return (
        <form>
          <input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleEmailChange} />
          <input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handlePasswordChange}/>
          <button type="button" onClick={this.handleLogin}>Login</button>
        </form>);
},
handleLogin: function() {
    console.log("EMail: " + this.state.email);
    console.log("Password: " + this.state.password);
}

工作小提琴。

此外,阅读文档,有一个完整的部分专门用于表单处理:表单

以前你也可以使用React的双向数据绑定助手mixin来实现同样的事情,但现在它被弃用了,取而代之的是设置值和更改处理程序(如上所述):

var ExampleForm = React.createClass({
  mixins: [React.addons.LinkedStateMixin],
  getInitialState: function() {
    return {email: '', password: ''};
  },
  handleLogin: function() {
    console.log("EMail: " + this.state.email);
    console.log("Password: " + this.state.password);
  },
  render: function() {
    return (
      <form>
        <input type="text" valueLink={this.linkState('email')} />
        <input type="password" valueLink={this.linkState('password')} />
        <button type="button" onClick={this.handleLogin}>Login</button>
      </form>
    );
  }
});

文档在这里:双向绑定助手。

另一种方法是使用ref属性并使用this.refs引用值。这里有一个简单的例子:

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

更多信息可以在React文档中找到: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-string-attribute

关于如何在React中使用单选按钮中描述的很多原因?这种方法并不总是最好的,但在一些简单的情况下确实是一种有用的替代方法。

我知道这个问题很老了,但我想到的最简单的解决方法是:

<form onSubmit={(e) => handleLogin(e)}>
   <input type="text" name="email" placeholder="Email" />
   <input type="password" name="password" placeholder="Password" />
   <button type="submit">Login</button>
</form>

你的handle函数:

const handleLogin = (e) => {
 e.preventDefault()
 const data = {
  email: e.target.elements.email.value,
  password: e.target.elements.password.value
 }
 console.log('FormData: ', data)
}

当你点击登录按钮时,你会在控制台看到如下格式的FormData: FormData:{电子邮件:'无论你在这里提示',密码:'也无论你在这里提示'}。

E.target.elements.email.value目标具有特定名称的元素,在这里是电子邮件和密码。

在console.log在handllogin之后,你可以做一些验证逻辑和登录逻辑。

下面是我使用单个inputChangeHandler收集多个表单输入的方法

import React from "react";

const COLORS = ["red", "orange", "yellow", "purple", "green", "white", "black"];

export default function App() {

  const initialFormFields = {
    name: undefined,
    email: undefined,
    favourite_color: undefined
  };
  const [formInput, setFormInput] = React.useState(initialFormFields);

  function inputChangeHandler(event) {
    setFormInput(prevFormState => ({
      ...prevFormState,
      [event.target.name]: event.target.value
    }))
  };

  return (
    <div className="App">
      <form>
        <label>Name: <input name="name" type="text" value={formInput.name} onChange={inputChangeHandler}/></label>
        <label>Email: <input name="email" type="email" value={formInput.email} onChange={inputChangeHandler}/></label>
        <div>
          {COLORS.map(color => <label><input type="radio" name="favourite_color" value={color} key={color} onChange={inputChangeHandler}/> {color} </label>)}
        </div>
      </form>

      <div>
        Entered Name: {formInput.name}
        Entered Email: {formInput.email}
        Favourite Color: {formInput.favourite_color}
      </div>
    </div>
  );
}