React+React Router V4+Semantic-UI-React:点击按钮同时新标签打开URL并跳转路由
解决React中同时打开新标签页链接+当前页面路由跳转的问题
你的问题根源在于**Link组件会阻止内部元素的默认跳转行为**——Link是react-router专门用来处理单页应用内部路由的组件,它在点击时会调用event.preventDefault(),所以你嵌套在里面的<a>标签的href和target="_blank"完全失效了,只有Link的to属性生效,导致只能完成当前页面的路由跳转,无法打开新标签页的外部链接。
下面给你两种可行的解决方案,分别适配类组件和函数组件:
方案一:类组件(适配你的代码结构)
我们可以去掉嵌套的Link和<a>,直接在按钮的点击事件里手动触发两个操作:用window.open()打开外部链接,用react-router的history.push()完成当前页面的路由跳转。需要借助withRouter高阶组件来获取history对象:
import { Button } from 'semantic-ui-react'; import { withRouter } from 'react-router-dom'; import * as React from 'react'; class YourComponent extends React.Component { state = { url: '' }; componentDidMount() { // 模拟从后端获取URL的逻辑 fetch('/your-api-url') .then(res => res.json()) .then(data => this.setState({ url: data.url })); } handleButtonClick = () => { // 1. 在新标签页打开外部链接 if (this.state.url) { window.open(this.state.url, '_blank'); } // 2. 当前页面跳转到指定路由 this.props.history.push('/path'); }; render() { return ( <Button size="small" fluid onClick={this.handleButtonClick} > Continue </Button> ); } } // 用withRouter包装组件,注入history属性 export default withRouter(YourComponent);
方案二:函数组件(如果后续重构为函数组件)
使用useHistory钩子获取history对象,逻辑和类组件一致:
import { Button } from 'semantic-ui-react'; import { useHistory } from 'react-router-dom'; import { useEffect, useState } from 'react'; function YourComponent() { const [url, setUrl] = useState(''); const history = useHistory(); useEffect(() => { // 从后端获取URL fetch('/your-api-url') .then(res => res.json()) .then(data => setUrl(data.url)); }, []); const handleButtonClick = () => { if (url) { window.open(url, '_blank'); } history.push('/path'); }; return ( <Button size="small" fluid onClick={handleButtonClick}> Continue </Button> ); } export default YourComponent;
关键说明
- 不要嵌套
Link和<a>:这两个组件都是处理点击跳转的,嵌套会导致事件冲突,Link的阻止默认行为会覆盖<a>的跳转逻辑。 - 手动控制两个操作:通过点击事件分别触发外部链接打开和内部路由跳转,完全避开组件间的事件冲突,同时满足你的需求。
内容的提问来源于stack exchange,提问作者joy08
相关产品推荐
相关产品推荐

