Material UI Button用作外部链接时桌面端正常移动端点击无响应
问题原因
Material UI 的Button组件默认渲染为原生<button>标签,桌面端浏览器对button上绑定的href属性做了兼容处理可以正常跳转,但移动端安卓、iOS的webkit内核浏览器不会识别button标签上的href属性,因此点击无响应。
修复方案
给类名为page的Button显式指定component="a"属性,让组件渲染为原生<a>标签,全端都能正常识别跳转属性,必要时可以加点击事件兜底:
const SwipeButtons = (props) => { return ( <div className='swipe-buttons'> {/* 新增component="a"属性,可选加onClick兜底跳转 */} <Button className='page' startIcon={<PageviewIcon/>} style={{color: 'rgb(38, 64, 179)'}} component="a" href={`${props.url}`} target='_blank' rel="noopener noreferrer" onClick={(e) => { // 兜底逻辑,兼容极端场景 if (!e.defaultPrevented) { window.open(props.url, '_blank') } }} > View Profile </Button> <Button className='fav' startIcon={<FavoriteIcon/>} style={{color: '#ef32d9'}}> Like </Button> </div> ) }
新增的
rel="noopener noreferrer"是为了避免新打开的页面能访问原页面的window对象,属于安全优化项,建议加上。
额外排查项
如果修改后仍有问题,可以检查以下配置:
- 确认
props.url是带http:///https://前缀的完整外部链接,缺少协议头会被移动端识别为站内路由跳转导致失效 - 检查
swipe-buttons父级元素有没有绑定touchstart/touchend事件并调用了e.preventDefault(),该操作会拦截原生a标签的跳转行为 - 确认移动端浏览器没有开启强制弹窗拦截,部分浏览器会默认拦截非用户主动触发的
_blank新标签页打开
内容的提问来源于stack exchange,提问作者Joel Gonzalez
相关产品推荐
相关产品推荐

