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

如何在Styled Components中正确实现Emotion属性选择器语法?

正确实现Styled Components中的属性选择器

你原来的代码存在两处问题:

  1. 对象语法里的属性选择器写法错误——既没使用&指代当前组件,键的格式也不符合JS对象规则
  2. 属性名大小写不匹配(Emotion中是data-isOn,你写的是data-ison)

下面是两种可行的正确实现方式:

方式一:对象语法

const Switch = styled('div')({
  cursor: 'pointer',
  // 用&指代当前组件,将完整选择器作为字符串键
  ['&[data-isOn="true"]']: {
    justifyContent: 'flex-end',
  },
});

方式二:模板字符串语法(更常用直观)

const Switch = styled.div`
  cursor: pointer;

  &[data-isOn="true"] {
    justify-content: flex-end;
  }
`;

使用组件时,记得添加对应属性:

<Switch data-isOn={true}>...</Switch>

注意:组件上的属性名必须和选择器里的完全一致(包括大小写),否则无法匹配生效。

内容的提问来源于stack exchange,提问作者sir-haver

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:50:24