组件聚焦时背景色切换失效求助(hover状态正常)
问题解决:CheckoutFormCard 选中与聚焦状态背景色不生效
你的问题出在CSS选择器的错误使用,以及聚焦状态的处理逻辑上,以下是无需引入状态的纯CSS修复方案:
问题分析
- 选中状态选择器错误:原样式中
input[type='radio']:checked + label完全不匹配你的DOM结构——input是嵌套在CardContainer(即label元素)内部的,而且input的下一个兄弟是icon而非label。 - 聚焦状态未处理:因为你把input设为
display: none,直接给input加:focus不会影响父容器,需要用:focus-within伪类来监听容器内元素的聚焦状态。 - theme调用语法错误:原选中状态样式里的
props.theme.purple缺少模板字符串包裹,无法正确读取主题变量。
修复后的样式代码
import { styled } from 'styled-components' export const CardContainer = styled.label` display: flex; flex-direction: row; align-items: center; gap: 0.75rem; padding: 1rem; cursor: pointer; background: ${(props) => props.theme['base-button']}; flex: 1 0 0; border-radius: 0.375rem; font-family: 'Roboto'; font-size: 0.75rem; font-style: normal; font-weight: 400; text-transform: uppercase; transition: background 0.2s; @media (max-width: 768px) { padding: 0.75rem; width: 100%; } &:hover { background: ${(props) => props.theme['base-hover']}; } // 修复:选中状态 - 用:has监听内部radio的checked状态 &:has(input[type='radio']:checked) { background: ${(props) => props.theme.purple}; } // 新增:聚焦状态 - 容器内input获焦时触发 &:focus-within { background: ${(props) => props.theme['base-hover']}; // 可选:添加outline增强可访问性 outline: 2px solid ${(props) => props.theme.purple}; } input { display: none; } svg { width: 1rem; height: 1rem; color: ${(props) => props.theme.purple}; } `
关键改动说明
&:has(input[type='radio']:checked):利用CSS:has()伪类,当label内部的radio被选中时,给整个label容器设置背景色,完美匹配你的DOM结构。&:focus-within:当容器内的input(即使是隐藏状态)获得焦点时,触发容器的样式变化,满足你需要的聚焦切换背景色需求,同时提升了组件的可访问性。- 修正了
props.theme.purple的模板字符串语法,确保主题变量正确渲染。
组件代码无需修改,保持原有结构即可正常工作。
内容的提问来源于stack exchange,提问作者Docta
相关产品推荐
相关产品推荐

