Html 在 JSX 和 React 中使用 onBlur

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24873485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:17:57  来源:igfitidea点击:

Using onBlur with JSX and React

htmlreactjsreactive-programmingreact-jsxonblur

提问by user3862066

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:

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

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

This is 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;
},

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

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

回答by Jared Forsyth

There are a few problems here.

这里有几个问题。

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

1:onBlur 需要回调,而您正在调用renderPasswordConfirmError并使用返回值,即 null。

2: you need a place to render the error.

2:你需要一个地方来呈现错误。

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.

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