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

React颜色生成器优化:点击提交时自动补全Hex色值的#前缀

解决Hex色值自动补全#前缀的问题

我开发的颜色生成器中,当用户仅输入Hex色值代码(如C4C4C4)而未添加#前缀时,程序无法正常运行。希望实现点击Submit按钮后自动补全该前缀,让用户无需手动输入#也能正常使用。

原核心代码

function App() {
  const [color, setColor] = useState("");
  const [error, setError] = useState(false);
  const [list, setList] = useState(new Values("#C4C4C4").all(10));

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      let colors = new Values(color).all(10);
      setList(colors);
    } catch (error) {
      setError(true);
      console.log(error);
    }
  };

  // 其余渲染代码省略...
}

解决方案

修改handleSubmit函数,在创建Values实例前先处理输入的颜色值:

  1. 去除输入前后的空格,避免用户误输入空格导致解析错误
  2. 判断处理后的颜色值是否以#开头,若没有则自动添加
  3. 成功生成颜色列表后重置错误状态,避免错误样式残留

修改后的完整代码

function App() {
  const [color, setColor] = useState("");
  const [error, setError] = useState(false);
  const [list, setList] = useState(new Values("#C4C4C4").all(10));

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      // 处理颜色值:去空格 + 补全#前缀
      let processedColor = color.trim();
      if (processedColor && !processedColor.startsWith('#')) {
        processedColor = `#${processedColor}`;
      }
      let colors = new Values(processedColor).all(10);
      setList(colors);
      setError(false); // 成功时重置错误状态
    } catch (error) {
      setError(true);
      console.log(error);
    }
  };

  return (
    <>
      <Navbar />
      <section className="container">
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={color}
            onChange={(e) => setColor(e.target.value)}
            placeholder="#C4C4C4"
            className={`${error ? "error" : null}`}
          />
          <button className="btn" type="submit">
            Submit
          </button>
        </form>
      </section>
      <section className="colors">
        {list.map((color, index) => {
          return (
            <SingleColor
              key={index}
              {...color}
              index={index}
              hexColor={color.hex}
            />
          );
        })}
      </section>
      <Footer />
    </>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:09:16