【问题标题】:React + React Router, handling all links to open in new tabReact + React Router,处理所有在新标签页中打开的链接
【发布时间】:2016-11-28 19:29:34
【问题描述】:

我有一个包含许多内部和外部链接的 React、Redux 和 Node 项目。我想让内部链接在同一页面中打开,而外部链接在新选项卡中打开。任何帮助或建议表示赞赏,

【问题讨论】:

标签: javascript node.js reactjs react-router


【解决方案1】:

您可以创建一个包装器组件,它决定链接是否是外部的,并使用适当的道具呈现<a> 元素。

以这种方式实现它会提高可重用性。

为什么会提高复用性?这里举几个例子:

  • 想象一下,一开始您有 20 个外部 URL,并且您手动管理它们的 props(没有包装器组件)。稍后您决定为每个外部网址添加一个新道具,您必须手动将其更改为 20 个位置。
  • URL 来自 API 响应,您必须在多个组件中列出它们。没有包装器组件 - 您将重复确定 URL 是否为外部的逻辑。

这是一个带有包装组件的示例:

// Define the Link wrapper component
class Link extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            target: props.target || this.getTarget(props.href)
        };
    }

    getTarget(url) {
        const siteDomain = 'stackoverflow.com';
        const isExternal = (url.indexOf(siteDomain) === -1);

        if (isExternal) return '_blank';

        return '_self';
    }

    render() {
        const props = Object.assign(this.props, ...this.state);
        return <a {...props}>{this.props.children}</a>
    }
}

// Use the Link wrapper
class Example extends React.Component{
    render() {
        return <Link href="http://google.com/">This is an external link</Link>
    }
}

【讨论】:

    【解决方案2】:

    外部链接应定义为a 元素,而不是Link 元素,以便您可以使用target="_blank" 在新选项卡中打开链接。

    【讨论】:

      猜你喜欢
      • 2015-07-24
      • 2020-05-13
      • 2017-02-22
      • 2016-10-26
      • 2011-09-11
      • 2011-09-29
      • 2013-11-30
      • 1970-01-01
      • 2017-07-16
      相关资源
      最近更新 更多