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

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(){…}访问电子邮件和密码字段?


当前回答

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

<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之后,你可以做一些验证逻辑和登录逻辑。

其他回答

如果你在项目中使用Redux,你可以考虑使用这个更高阶的组件https://github.com/erikras/redux-form。

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

<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之后,你可以做一些验证逻辑和登录逻辑。

像这样给你的输入参考

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

不需要使用引用,你可以使用事件访问

function handleSubmit(e) {
    e.preventDefault()
    const {username, password } = e.target.elements
    console.log({username: username.value, password: password.value })
}

<form onSubmit={handleSubmit}>
   <input type="text" id="username"/>
   <input type="text" id="password"/>
   <input type="submit" value="Login" />
</form>

我像这样使用React Component state:

<input type="text" name='value' value={this.state.value} onChange={(e) => this.handleChange(e)} />

handleChange(e){
   this.setState({[e.target.name]: e.target.value})
}`