mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
22776c2eee
* Immplement the initial singleton Router. * Use the new SingletonRouter for HMR error handling. * Use SingletonRouter inside the Link. * Create an example app using the Router. * Make the url parameter optional in Router.push and Router.replace * Add a section about next/router in the README.
70 lines
1.7 KiB
JavaScript
70 lines
1.7 KiB
JavaScript
import React, { Component, Children } from 'react'
|
|
import Router from './router'
|
|
|
|
export default class Link extends Component {
|
|
constructor (props) {
|
|
super(props)
|
|
this.linkClicked = this.linkClicked.bind(this)
|
|
}
|
|
|
|
linkClicked (e) {
|
|
if (e.target.nodeName === 'A' &&
|
|
(e.metaKey || e.ctrlKey || e.shiftKey || (e.nativeEvent && e.nativeEvent.which === 2))) {
|
|
// ignore click for new tab / new window behavior
|
|
return
|
|
}
|
|
|
|
const { href, scroll, as } = this.props
|
|
|
|
if (!isLocal(href)) {
|
|
// ignore click if it's outside our scope
|
|
return
|
|
}
|
|
|
|
e.preventDefault()
|
|
|
|
const route = as ? href : null
|
|
const url = as || href
|
|
|
|
// straight up redirect
|
|
Router.push(route, url)
|
|
.then((success) => {
|
|
if (!success) return
|
|
if (scroll !== false) window.scrollTo(0, 0)
|
|
})
|
|
.catch((err) => {
|
|
if (this.props.onError) this.props.onError(err)
|
|
})
|
|
}
|
|
|
|
render () {
|
|
const children = Children.map(this.props.children, (child) => {
|
|
const props = {
|
|
onClick: this.linkClicked
|
|
}
|
|
|
|
const isAnchor = child && child.type === 'a'
|
|
|
|
// if child does not specify a href, specify it
|
|
// so that repetition is not needed by the user
|
|
if (!isAnchor || !('href' in child.props)) {
|
|
props.href = this.props.as || this.props.href
|
|
}
|
|
|
|
if (isAnchor) {
|
|
return React.cloneElement(child, props)
|
|
} else {
|
|
return <a {...props}>{child}</a>
|
|
}
|
|
})
|
|
|
|
return children[0]
|
|
}
|
|
}
|
|
|
|
export function isLocal (href) {
|
|
const origin = window.location.origin
|
|
return !/^https?:\/\//.test(href) ||
|
|
origin === href.substr(0, origin.length)
|
|
}
|