将onBlur与JSX和React结合使用 [英] Using onBlur with JSX and React

查看:500
本文介绍了将onBlur与JSX和React结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个密码确认功能,该功能仅在用户离开确认字段后才显示错误.我正在使用Facebook的React JS.这是我的输入组件:

I am trying to create a password confirmation feature that renders an error only after a user leaves the confirmation field. I'm working with Facebook's React JS. This is my input component:

<input
    type="password"
    placeholder="Password (confirm)"
    valueLink={this.linkState('password2')}
    onBlur={this.renderPasswordConfirmError()}
 />

这是renderPasswordConfirmError:

This is renderPasswordConfirmError :

renderPasswordConfirmError: function() {
  if (this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

当我运行页面时,输入冲突的密码时不会显示该消息.

When I run the page the message is not displayed when conflicting passwords are entered.

推荐答案

这里有一些问题.

1:onBlur需要回调,并且您正在调用renderPasswordConfirmError并使用返回值,该值为空.

1: onBlur expects a callback, and you are calling renderPasswordConfirmError and using the return value, which is null.

2:您需要一个呈现错误的地方.

2: you need a place to render the error.

3:您需要一个标记来跟踪和我正在验证",您将在模糊时将其设置为true.您可以根据需要将其设置为false.

3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.

handleBlur: function () {
  this.setState({validating: true});
},
render: function () {
  return <div>
    ...
    <input
        type="password"
        placeholder="Password (confirm)"
        valueLink={this.linkState('password2')}
        onBlur={this.handleBlur}
     />
    ...
    {this.renderPasswordConfirmError()}
  </div>
},
renderPasswordConfirmError: function() {
  if (this.state.validating && this.state.password !== this.state.password2) {
    return (
      <div>
        <label className="error">Please enter the same password again.</label>
      </div>
    );
  }  
  return null;
},

这篇关于将onBlur与JSX和React结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆