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

React内联CSS对象中clamp函数与:focus伪类写法报错如何解决?

问题原因分析

  • clamp报错原因:你把CSS的clamp()函数当成了JS函数直接调用,React内联样式里所有CSS函数都需要作为字符串值传递,不能直接写JS函数式的调用。另外你代码里的${COLOR_NOT_BLACK}这类变量插值也没有用反引号包裹模板字符串,会导致变量无法正常解析。
  • &:focus报错原因:原生React内联样式不支持嵌套伪类、&选择器这类CSS预处理器/CSS-in-JS专属语法,&是styled-components、Emotion这类第三方样式库才支持的语法,原生内联样式无法识别。

修正方案

方案1:使用原生React内联样式+状态控制聚焦效果

不需要引入额外依赖,用React状态监听聚焦/失焦事件动态切换样式:

import { useState } from 'react';

// 替换为你的实际色值
const COLOR_NOT_BLACK = '#222';
const COLOR_SALMON = '#fa8072';

const PhoneInput = () => {
  // 管理聚焦状态
  const [isFocused, setIsFocused] = useState(false);

  const PhoneInputStyle = {
    fontSize: "clamp(13px, 1.111vw, 16px)",
    lineHeight: "clamp(15px, 1.319vw, 19px)",
    position: "relative",
    width: "100%",
    height: "51px",
    cursor: "pointer",
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    padding: "8px 16px",
    // 模板字符串用反引号包裹才能解析变量
    border: isFocused ? `1px solid ${COLOR_SALMON}` : `1px solid ${COLOR_NOT_BLACK}`,
    boxSizing: "border-box",
    borderRadius: "10px",
    outline: "none",
    gridRowStart: "1",
    gridColumnStart: "1"
  };

  return (
    <input
      style={PhoneInputStyle}
      onFocus={() => setIsFocused(true)}
      onBlur={() => setIsFocused(false)}
      type="tel"
    />
  );
};

注:原生React内联样式中写!important不会生效,内联样式本身优先级高于普通类选择器,一般场景不需要再加!important,如果需要覆盖更高优先级的样式,可以改用CSS类名+全局样式的方案实现。

方案2:使用CSS-in-JS库(比如styled-components)

如果你项目中已经引入了这类样式库,直接修正语法即可:

import styled from 'styled-components';

// 替换为你的实际色值
const COLOR_NOT_BLACK = '#222';
const COLOR_SALMON = '#fa8072';

const PhoneInput = styled.input`
  font-size: clamp(13px, 1.111vw, 16px);
  line-height: clamp(15px, 1.319vw, 19px);
  position: relative;
  width: 100%;
  height: 51px;
  cursor: pointer;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 8px 16px;
  border: 1px solid ${COLOR_NOT_BLACK};
  box-sizing: border-box;
  border-radius: 10px;
  outline: none;
  grid-row-start: 1;
  grid-column-start: 1;

  &:focus {
    border: 1px solid ${COLOR_SALMON} !important;
  }
`;

// 组件内直接调用即可:<PhoneInput type="tel" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:36:07