【问题标题】:Update className style dynmically based on state根据状态动态更新 className 样式
【发布时间】:2020-10-08 21:16:18
【问题描述】:

我在我的项目中使用 React Hooks,如果状态的值发生变化,我需要尝试解决如何动态地将类添加到 className。我正在使用react-hook-form 来验证我的表单。

RegisterForm.jsx

<input
  className={styles.authoriseInput}
  placeholder="Email"
  name="email"
  ref={register({required: true, minLength: 4})}  # supposed to be a regex, but too long for this question
/>
{errors.email &&
  <p className={styles.errors}>Please enter a valid email.</p>
}

第二部分工作正常,当出现错误时,会显示&lt;p&gt; 标签。但我被困在如何以同样的方式更新inputclassName 属性。我想为authoriseInput 添加一个样式,当error.email 被触发时设置border-color

非常感谢任何建议。

谢谢!

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    您可以像渲染组件一样有条件地设置classNames

    <input
      className={errors.email && styles.authoriseInput}
      placeholder="Email"
      name="email"
      ref={register({required: true, minLength: 4})}  # supposed to be a regex, but too long for this question
    />
    {errors.email &&
      <p className={styles.errors}>Please enter a valid email.</p>
    }
    

    【讨论】:

    • 如果error.email 为假,这只会导致未定义
    • 我同意,这取决于您的预期结果。如果你想增加一个类,我总是更喜欢className={[styles.authoriseInput, errors.email &amp;&amp; styles.errorInput]},正如stackoverflow.com/a/40824714/13745258 中讨论的那样。这样,您继承了基本输入样式,并且仅通过错误样式进行扩展
    • 所以预期的结果是输入将保持其当前样式,但会在其周围出现红色边框(想象任何网站上的无效输入用于登录)。 @sebastian 建议的内容最终会出现错误,因为它总是错误的,并且您上面提到的内容根本没有设置输入样式。我会继续玩。
    • @intRG 这很奇怪。 styles.authoriseInput 的值是多少。你最终会混淆StylesheetClassNames 的使用吗?
    • @sebastian 我更新了问题以进行澄清
    【解决方案2】:

    向 className 属性添加条件

    <input
       className={errors.email ? styles.errorInput : styles.authoriseInput}
       placeholder="Email"
       name="email"
       ref={register({required: true, minLength: 4})}  # supposed to be a regex, but too 
       long for this question
    />
    {errors.email &&
        <p className={styles.errors}>Please enter a valid email.</p>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-18
      • 2022-09-28
      • 2014-08-30
      • 2019-10-23
      • 1970-01-01
      • 2021-12-09
      • 2021-03-27
      • 2016-07-05
      相关资源
      最近更新 更多