React-router4 第五篇 Preventing Transitions 防止转换

时间:2023-03-08 21:58:45

文档地址:https://reacttraining.com/react-router/web/example/preventing-transitions

大概意思就是说:我在这个页面上写东西呢?不小心点到了其他路由上,我们可以做一个提示,来一个弹窗,提示你真的要切换走吗?然后选择确定和取消,

关键代码就是

<Prompt
when={isBlocking} // when 值为true时启用防止转换
message={(location, a,b) => { // 验证出,这个属性会传入2个参数。。。
console.log(location) // 是一个对象,内含 hash key pathname search state
console.log(a) // PUSH ??不能明白这个字符串是啥
console.log(b) // undefind
return `Are you sure you want to go to ${location.pathname}`
}}
/>
import React from 'react'
import ReactDOM from 'react-dom'
import {
BrowserRouter as Router,
Route,
Link,
Prompt
} from 'react-router-dom' const PreventingTransitionsExample = () => (
<Router>
<div>
<ul>
<li><Link to="/">Form</Link></li>
<li><Link to="/one">One</Link></li>
<li><Link to="/two">Two</Link></li>
</ul>
<Route path="/" exact component={Form}/>
<Route path="/one" render={() => <h3>One</h3>}/>
<Route path="/two" render={() => <h3>Two</h3>}/>
</div>
</Router>
) class Form extends React.Component {
state = {
isBlocking: false
} render() {
const { isBlocking } = this.state return (
<form
onSubmit={event => {
event.preventDefault()
event.target.reset()
this.setState({
isBlocking: false
})
}}
>
<Prompt
when={isBlocking}
message={location => (
`Are you sure you want to go to ${location.pathname}` // ES6的模板字符串
)}
/> <p>
Blocking? {isBlocking ? 'Yes, click a link or the back button' : 'Nope'}
</p> <p>
<input
size="50"
placeholder="type something to block transitions"
onChange={event => {
this.setState({
isBlocking: event.target.value.length > 0
})
}}
/>
</p> <p>
<button>Submit to stop blocking</button>
</p>
</form>
)
}
}
ReactDOM.render(
<PreventingTransitionsExample />,
document.getElementById("app")
)