由于我在React应用程序中使用React路由器来处理我的路由,我很好奇是否有一种方法可以重定向到外部资源。
比如有人打人:
example.com/privacy-policy
我希望它重定向到:
example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
我发现在我的index.html加载中,避免用纯JavaScript编写它完全没有任何帮助:
if (window.location.path === "privacy-policy"){
window.location = "example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
}
用react-router的Link组件就可以做到。在“to”道具中,您可以指定3种类型的数据:
a string: A string representation of the Link location, created by concatenating the location’s pathname, search, and hash properties.
an object: An object that can have any of the following properties:
pathname: A string representing the path to link to.
search: A string representation of query parameters.
hash: A hash to put in the URL, e.g. #a-hash.
state: State to persist to the location.
a function: A function to which current location is passed as an argument and which should return location representation as a string or as an object
对于你的例子(外部链接):
https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies
您可以执行以下操作:
<Link to={{ pathname: "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies" }} target="_blank" />
您还可以传递您想要的道具,如标题,id, className等。
补充一下Víctor Daniel的回答:链接的路径名实际上只有在链接前有“https://'”或“http://'”时才会把你带到外部链接。
您可以执行以下操作:
<Link to={{ pathname:
> "https://example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies"
> }} target="_blank" />
或者如果你的URL没有'https://', ',我会这样做:
<Link to={{pathname:`https://${link}`}} target="_blank" />
否则它将位于当前基路径的前面,如Lorenzo Demattécommented。