移动端视图下styled-components封装的Button组件onClick事件失效如何解决
问题原因
- 核心问题是CSS选择器的语法错误:代码中
& :hover、& :focus的&和伪类之间多了空格,空格在CSS选择器中代表后代选择器,这两条规则实际会作用于DateElement的所有子元素,而非组件本身。 - 移动端触摸操作触发点击的流程是:
touchstart→focus→click,当你点击按钮时,内部的Typography子元素会先触发focus状态,匹配到& :focus { display: none; }规则后直接隐藏,点击的目标元素丢失,绑定在父元素上的onClick事件自然不会触发。 - 桌面端没有复现是因为桌面端鼠标点击默认不会让普通文本子元素触发
focus状态,因此不会触发子元素隐藏的逻辑。
修复方案
- 删掉
&和伪类之间的空格,让hover、focus规则作用于DateElement组件本身。 - 修改错误的
focus样式:你原本的需求应该是去掉按钮默认的focus轮廓,应该用outline: none而非display: none,后者会直接隐藏元素,完全不符合使用预期。 - 可选优化:添加
touch-action: manipulation规则,禁用浏览器默认的双击缩放等行为,消除移动端300ms点击延迟。
修复后的组件定义代码如下:
const DateElement = styled.button` background-color: ${(props) => (props.primary ? '#DEE2FF' : '#696B86')}; color: ${(props) => (props.primary ? 'black' : '#dedee4')}; box-shadow: none; padding: 9px; width: 90px; text-align: center; height: 90px; user-select: none; border: 1px solid rgba(20, 79, 118, 0.2); touch-action: manipulation; &:hover { cursor: pointer; } &:focus { outline: none; } ${(theme) => theme.theme.breakpoints.down('sm')} { padding: 3px; width: 70px; text-align: center; height: 70px; } `;
内容的提问来源于stack exchange,提问作者Andrés Manco
相关产品推荐
相关产品推荐

