有一个特定的组件react-router
仅用于该特定目的:<Prompt>
引用自述文件:
用于在离开页面之前提示用户。当您的应用程序进入应阻止用户导航离开的状态时(如表单填写一半),渲染<Prompt>
.
在<Prompt>
有when
和message
props。当用户尝试离开并when
设置为 true时会显示提示。因此,您可以让函数根据您的要求将一些 bool 变量设置为 true/false,并将其作为props传递给<Prompt>
.
例如:
//your component where you get user input
state = {
name: "",
};
render() {
return (
<div>
<div>
<Prompt
when={!!this.state.name} /* triggers the display of prompt */
/*(checks if this.state.name is set)*/
message={location => `You have unsaved changes. Are you sure you want to go to ${location.pathname}?`}
/>
<div>Nice looking profile! What's your name?</div>
<input value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />
</div>
</div>
);
}

Codesandbox 示例(不是我的)
在这里找到教程
在<Prompt>
此处查看文档:docs