小编典典

在JSX和React中使用onBlur

reactjs

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

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

这是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;
},

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


阅读 1683

收藏
2020-07-22

共1个答案

小编典典

这里有一些问题。

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

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

3:您需要一个标记来跟踪“和我正在验证”,在模糊时将其设置为true。如果需要,可以将其设置为false,具体取决于所需的行为。

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;
},
2020-07-22