在我的render函数中有一个简单的形式,如下所示:

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

要访问EmailPassword字段,我应该在handleLogin: function() { ... }中写什么?

推荐答案

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

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

工作fiddle分钟.

此外,阅读文档,有一整节专门讨论表单处理:Forms

以前,您也可以使用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>
    );
  }
});

文件在这里:Two-way Binding Helpers.

Javascript相关问答推荐

主要内部的ExtJS多个子应用程序

格式值未保存在redux持久切片中

基于变量切换隐藏文本

如何从html元素创建树 struct ?

无法检测卡片重叠状态的问题

还原器未正确更新状态

JavaScript是否有多个`unfined`?

为什么JPG图像不能在VITE中导入以进行react ?

在SHINY R中的嵌套模块中,不能使用Java代码

MongoDB受困于太多的数据

令牌JWT未过期

基于产品ID更新条带产品图像的JavaScript命中错误

将范围 Select 器添加到HighChart面积图

使用线性插值法旋转直线以查看鼠标会导致 skip

在JavaScript中,有没有一种方法可以迭代字符串的词法标记?

使用createBrowserRoutVS BrowserRouter的Reaction路由

在没有任何悬停或其他触发的情况下连续交换图像

从异步操作返回对象

如何在css中裁剪成一定Angular 的圆的一部分,而不需要复杂的多边形

如果我将高度设置为其内容的100%,则在Java脚本中拖动以调整面板大小时会冻结