如何在反应应用程序中将外部链接显示为弹出窗口?
How to show external links as popup in react application?
在我的 React 应用程序中,当我单击外部 link 假设 http://www.example.com/about 时,我不希望它重定向到该网站,但我希望关于页面呈现为弹出窗口我的反应应用程序。我该如何处理?
您可以为链接创建一个包装器组件,以检查 href
属性是否与您的网站位置匹配或转到第 3 方站点,并呈现普通的 a
标签或内部带有 iframe 的模态对话框。
例如。 Link.js
import React, { Component, Fragment } from 'react'
import Modal from '...' // any of the available modal component for react
export default class Link extends Component {
state = { isOpen: false }
render () {
const url = new URL(this.props.href)
if (url.hostname === WEBSITE_HOSTNAME) return (
<a href={this.props.href}>{this.props.children}</a>
)
return (
<Fragment>
// you could also use an <a> here if you want users to be able to open the link in a new tab with a right click
<button onClick={() => this.setState({ modalOpen: true })}>{this.props.children}</button>
<Modal isOpen={this.state.isOpen}>
<iframe src={this.props.href} />
</Modal>
</Fragment>
)
}
}
更好的是,将它分成两个部分,因为常规链接不需要任何状态...
在我的 React 应用程序中,当我单击外部 link 假设 http://www.example.com/about 时,我不希望它重定向到该网站,但我希望关于页面呈现为弹出窗口我的反应应用程序。我该如何处理?
您可以为链接创建一个包装器组件,以检查 href
属性是否与您的网站位置匹配或转到第 3 方站点,并呈现普通的 a
标签或内部带有 iframe 的模态对话框。
例如。 Link.js
import React, { Component, Fragment } from 'react'
import Modal from '...' // any of the available modal component for react
export default class Link extends Component {
state = { isOpen: false }
render () {
const url = new URL(this.props.href)
if (url.hostname === WEBSITE_HOSTNAME) return (
<a href={this.props.href}>{this.props.children}</a>
)
return (
<Fragment>
// you could also use an <a> here if you want users to be able to open the link in a new tab with a right click
<button onClick={() => this.setState({ modalOpen: true })}>{this.props.children}</button>
<Modal isOpen={this.state.isOpen}>
<iframe src={this.props.href} />
</Modal>
</Fragment>
)
}
}
更好的是,将它分成两个部分,因为常规链接不需要任何状态...