由于我在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 v4兼容。
它使用的是TypeScript,但转换为原生JavaScript应该相当简单:
interface Props {
exact?: boolean;
link: string;
path: string;
sensitive?: boolean;
strict?: boolean;
}
const ExternalRedirect: React.FC<Props> = (props: Props) => {
const { link, ...routeProps } = props;
return (
<Route
{...routeProps}
render={() => {
window.location.replace(props.link);
return null;
}}
/>
);
};
与…一起使用:
<ExternalRedirect
exact={true}
path={'/privacy-policy'}
link={'https://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等。