【问题标题】:Using onBlur with JSX and React在 JSX 和 React 中使用 onBlur
【发布时间】:2014-09-12 10:53:01
【问题描述】:

我正在尝试创建一个密码确认功能,该功能仅在用户离开确认字段后才呈现错误。我正在使用 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;
},

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

【问题讨论】:

    标签: html reactjs reactive-programming react-jsx onblur


    【解决方案1】:

    这里有一些问题。

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 2021-05-03
      • 2017-05-06
      • 2017-07-27
      • 2021-01-21
      • 2021-09-06
      相关资源
      最近更新 更多