我的React应用程序中有一个页面,如果表单脏了,我想阻止用户离开。
在我的反应路线中,我正在使用onLeave道具,如下所示:
<Route path="dependent" component={DependentDetails} onLeave={checkForm}/>
我的onLeave
是:
const checkForm = (nextState, replace, cb) => {
if (form.IsDirty) {
console.log('Leaving so soon?');
// I would like to stay on the same page somehow...
}
};
有没有一种方法可以防止触发新路由并使用户停留在同一页面上?
为时已晚,但是根据React Router Documentation
,可以在React Router Documentation
组件的帮助下使用preventing transition
。
<prompt>
如果 <Prompt
when={isBlocking}
message={location =>
`Are you sure you want to go to ${location.pathname}`
}
/>
等于isBlocking
,则显示一条消息。有关更多信息,请阅读文档。
我认为自从Lazarev回答以来,推荐的方法已经改变,因为他的链接示例当前不再位于true
文件夹中。相反,我认为您应该按照examples
的定义:
this example
然后将componentWillMount() {
this.props.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
},
定义为返回将出现在确认警报中的字符串的函数。
UPDATE
先前的链接现在已过期且不可用。在较新版本的React Router中,似乎有一个新组件routerWillLeave
可用于取消/控制导航。参见Prompt
React-router api在此类情况下提供了this example对象,您可以在正在使用的组件的Transition
生命周期方法中创建钩子。有点像(代码来自github上的react-router Transition
):
willTransitionTo
现在,我们可以通过Prompt组件+ getUserConfirmation编写自定义阻止对话框
有关详细信息,请观看视频:
EN:examplesRU:var Form = React.createClass({
mixins: [ Router.Navigation ],
statics: {
willTransitionFrom: function (transition, element) {
if (element.refs.userInput.getDOMNode().value !== '') {
if (!confirm('You have unsaved information, are you sure you want to leave this page?')) {
transition.abort();
}
}
}
},
handleSubmit: function (event) {
event.preventDefault();
this.refs.userInput.getDOMNode().value = '';
this.transitionTo('/');
},
render: function () {
return (
<div>
<form onSubmit={this.handleSubmit}>
<p>Click the dashboard link with text in the input.</p>
<input type="text" ref="userInput" defaultValue="ohai" />
<button type="submit">Go</button>
</form>
</div>
);
}
});