我有几个标签供用户填写。每个标签都有一个保存按钮,此按钮保存特定于当前标签的数据。 如果相关,我使用ReactJS,Redux来创建网站。问题是如何确保(强制)用户在切换到另一个选项卡之前单击“保存”按钮?
答案 0 :(得分:1)
使用react-router-dom
尝试链接和提示,假设您使用的是:
import React from 'react'
import {
BrowserRouter as Router,
Route,
Link,
Prompt
} from 'react-router-dom'
const Index = () => (
<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
style={{ marginTop: '100px' }}
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}`
)}
/>
<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>
<Link to="/">CLICK HERE TO NAVIGATE</Link>
</form>
)
}
}
export default Index
我刚尝试运行此代码,它在现有项目中运行。
请参阅:https://reacttraining.com/react-router/web/example/preventing-transitions
这将挂钩您的路由器并检测导航更改,并在检测到导航时通过<Prompt />
抛出消息。