You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为React组件应用多条件样式?表单输入框三色边框实现

输入框三种边框状态实现方案

要实现输入框的三种边框状态(初始灰色、非空蓝色、提交错误红色),需要添加错误状态跟踪并调整组件的样式逻辑,具体步骤如下:

1. 页面组件新增错误状态

在页面的状态定义中添加一个serialError状态,用于标记提交时的错误状态:

import { useState } from 'react';

// 其他原有状态...
const [serial, setSerial] = useState("");
const [serialError, setSerialError] = useState(false); // 新增错误状态

2. 修正提交函数逻辑

修改handleSumit函数的判断逻辑(注意serial是字符串类型,不能用===0判断空值),当输入为空时设置错误状态,否则提交前重置错误状态:

const handleSumit = function (e) {
  e.preventDefault();
  
  // 先重置错误状态
  setSerialError(false);

  if (!serial.trim()) { // 判断输入是否为空(去除首尾空格)
    setSerialError(true); // 触发错误状态
    return; // 阻止后续提交逻辑
  }

  let form = {
    idinformacion: compania,
    iddepartamento: departamento,
    idunidad: unidad,
  };

  let Data = JSON.stringify(form);
  ServiceSerial.Create(Data);
};

3. 给InputGroup组件传递错误状态

调用InputGroup时新增isError属性,将错误状态传递给子组件:

<InputGroup
  input_label={"Serial"}
  input_type={"text"}
  input_value={serial}
  input_placeholder={"Serial"}
  state_name={serial}
  set_state_name={setSerial}
  on_change={hanleSerial}
  isError={serialError} // 新增传递错误状态
/>

4. 修改InputGroup组件处理错误状态

更新InputGroup的props定义,接收isError参数,并根据输入值和错误状态动态生成类名:

const InputGroup = function ({
  input_label,
  input_type,
  input_value,
  input_name,
  input_placeholder,
  on_change,
  on_key_down,
  isError // 新增接收错误状态
}) {
  // 优先级:错误状态 > 非空状态 > 默认状态
  const inputClass = isError ? "Error" : (input_value ? "Activated" : "");

  return (
    <InputGroupContainer>
      <Label>{input_label}</Label>
      <WrapperInput>
        <Input
          type={input_type}
          placeholder={input_placeholder}
          value={input_value}
          name={input_name}
          onChange={on_change}
          onKeyDown={on_key_down}
          className={inputClass} // 使用动态生成的类名
        />
      </WrapperInput>
      {/* <span>{errorMessage}</span> */}
    </InputGroupContainer>
  );
};

5. 添加错误状态的CSS样式

在Input的styled组件中新增.Error类的样式,定义错误时的红色边框:

export const Input = styled.input`
  font-size: 16px;
  font-weight: normal;
  font-family: "Inter";
  letter-spacing: 0.3px;
  width: 100%;
  height: 40px;
  line-height: 40px;
  padding: 0px 5px 0px 10px;
  border: 2px solid #ccc; /* 初始灰色 */
  border-radius: 3px;
  transition: 0.3s ease all;
  color: black;
  
  &:focus {
    outline: none;
    border: 2px solid #00aea9;
  }

  &.Activated {
    border: 2px solid #00aea9; /* 非空蓝色 */
  }

  &.Error {
    border: 2px solid #ff4444; /* 错误红色,可根据需求调整颜色值 */
  }
`;

补充:清空按钮重置错误状态

在hanleClear函数中添加错误状态重置,避免清空输入后错误样式残留:

const hanleClear= () => {
  // 其他原有重置代码...
  setSerial("");
  setSerialError(false); // 重置错误状态
};

完成以上修改后,输入框即可实现三种状态:

  • 组件加载时:边框为灰色(#ccc)
  • 输入框非空时:边框为蓝色(#00aea9)
  • 点击Register按钮且输入为空时:边框变为红色(#ff4444)

内容的提问来源于stack exchange,提问作者Alexandra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:50:24