使用 react-router-dom 重定向到第三方 url
Redirect to third party url using react-router-dom
我非常了解react-router-dom我想做一个组件的条件渲染。如果使用未登录,则将他重定向到某个第三方 URL
例如,下面的代码看起来很简洁并且工作正常
<Route exact path="/home" render={() => (
isLoggedIn() ? (
<Redirect to="/front"/>
) : (
<Home />
)
)}/>
假设在上面的例子中,如果我想重定向 to
https://www.google.com 我该怎么做?
如果我写
<Redirect to="https://www.google.com"> it gives me error.
如何重定向到第三方网站?
您可以为外部网址使用标签,
<a href='https://domain.extension/external-without-params'>external</a>
但您也可以提供这样的组件:
<Route path='/external' component={() => { window.location = 'https://domain.extension/external-without-params'; return null;} }/>
您可以使用 window.open()
重定向到任何网站。
例如:
window.open('https://www.google.com');
在您的代码中实现重定向:
render () {
if(this.isLogin) {
return(/* your components*/);
} else {
window.open('https://www.google.com');
return (<div></div>); //render function should return something
}
}
您还可以指定目标属性或 window 的名称,有关详细信息,请参阅 w3school tutorial about this function。
请记住,您不能使用 <Link />
或 <NavLink />
执行此操作,因为它们主要用于在整个单页应用程序中进行路由。
您应该改用锚标记。
示例:<a href="https://www.google.com">Google</a>
.
可以轻松地使用一个按钮,只需这样做:
<button onClick={(e) => (window.location = 'https://www.google.com')}>Click me</button>
如果您使用的是 Typescript,您可能会在已接受的答案中收到以下错误:
Type 'string' is not assignable to type 'Location'
要解决这个问题,您只需要使用 window.location.href
<Route path="/external" component={() => {window.location.href = config.UPGRADE_URL return null }} />
我非常了解react-router-dom我想做一个组件的条件渲染。如果使用未登录,则将他重定向到某个第三方 URL
例如,下面的代码看起来很简洁并且工作正常
<Route exact path="/home" render={() => (
isLoggedIn() ? (
<Redirect to="/front"/>
) : (
<Home />
)
)}/>
假设在上面的例子中,如果我想重定向 to
https://www.google.com 我该怎么做?
如果我写
<Redirect to="https://www.google.com"> it gives me error.
如何重定向到第三方网站?
您可以为外部网址使用标签,
<a href='https://domain.extension/external-without-params'>external</a>
但您也可以提供这样的组件:
<Route path='/external' component={() => { window.location = 'https://domain.extension/external-without-params'; return null;} }/>
您可以使用 window.open()
重定向到任何网站。
例如:
window.open('https://www.google.com');
在您的代码中实现重定向:
render () {
if(this.isLogin) {
return(/* your components*/);
} else {
window.open('https://www.google.com');
return (<div></div>); //render function should return something
}
}
您还可以指定目标属性或 window 的名称,有关详细信息,请参阅 w3school tutorial about this function。
请记住,您不能使用 <Link />
或 <NavLink />
执行此操作,因为它们主要用于在整个单页应用程序中进行路由。
您应该改用锚标记。
示例:<a href="https://www.google.com">Google</a>
.
可以轻松地使用一个按钮,只需这样做:
<button onClick={(e) => (window.location = 'https://www.google.com')}>Click me</button>
如果您使用的是 Typescript,您可能会在已接受的答案中收到以下错误:
Type 'string' is not assignable to type 'Location'
要解决这个问题,您只需要使用 window.location.href
<Route path="/external" component={() => {window.location.href = config.UPGRADE_URL return null }} />