【问题标题】:Why my input field with required show error as initial state?为什么我的输入字段需要显示错误作为初始状态?
【发布时间】:2025-11-30 08:35:01
【问题描述】:

我有一个用户需要填写的输入字段。 呈现页面时,我希望输入字段显示没有错误红色边框,因为没有传递任何值,我只想在用户键入一些值然后删除它时触发错误。

我想要的行为

问题,我需要在初始渲染时移除这个红色边框

这里是代码

<div className="ipt-form-group">
      <input type="number" required className={this.state.activeCSS} placeholder="Qual a média de faturamento mensal?" min="0" onInput={this.changeView.bind(this)} onChange={this.changeRevenuesState.bind(this)}/>
    </div>
    <div className="ipt-form-group">
      <input type="number" required className={this.state.activeCSS} placeholder="Qual a média de despesas fixas mensais?" min="0" onInput={this.changeView.bind(this),() => this.callbackFunction()} onChange={this.changeAverageState.bind(this)}/>
    </div>

【问题讨论】:

  • 欢迎来到 Stack Overflow!仅从以上信息我们无法为您提供帮助。请使用 Stack Snippets([&lt;&gt;] 工具栏按钮)通过 runnable minimal reproducible example 更新您的问题。 Stack Snippets 支持 React,包括 JSX; here's how to do one.

标签: javascript css html reactjs input


【解决方案1】:

您需要在表单上的keyup 上启动验证。 我认为你需要这样的东西:

var validationRules = {
  city: {
    message: 'City cannot be empty',
    rule: 'notEmpty'
  },
  address: {
    message: 'Address cannot be empty',
    rule: 'notEmpty'
  }
};

var $inputs = $('#myForm :input');

var values = {};
$inputs.each(function() {
  $(this).on('keyup', function() {
    validation(this, validationRules[this.name]);
  });
});



function validation (input, ruleObj) {
  var isInvalid =  false;

  if (ruleObj.rule === 'notEmpty') {
    if(input.value === '') {
      isInvalid = true;
    } else {
      isInvalid = false;
    }
  }
  if(isInvalid) {
    $(input).addClass('is-invalid');
  } else {
    $(input).removeClass('is-invalid');
  }

  console.log('Validated: ' + input.name);
}
.is-invalid {
  border: 1px solid #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  <label>Address</label>
  <input type="text" name="address">
  <label>City</label>
  <input type="text" name="city">
</form>

(当然你可以替换 jQuery。正如@Lojka 所说,将它与 react 混合是不好的做法)

【讨论】:

  • 他正在使用reactjs,将它与jquery混合使用是不好的做法。
  • 是的,你说得对。这只是一个例子。你可以替换jQuery。
  • 你是最好的兄弟!哈哈哈干得漂亮。
  • Cool:) 如果它有效,那么您可以接受我的回答
【解决方案2】:

创建你的组件,这样它将获得showBorder 属性。

然后您可以创建默认为false 的商店,并在任何更新后将其更改为true

您的商店将处理此输入的所有道具

阅读通量/还原 https://facebook.github.io/flux/docs/in-depth-overview.html#content

【讨论】: