单击取消按钮时显示提示 react-router v4

Show Prompt react-router v4 on click CANCEL button

我知道我可以使用以下代码片段来防止用户导航到另一个选项卡而不提醒他们他们可能会丢失输入的数据。

import { Prompt } from 'react-router'

const MyComponent = () => [
    <Prompt
      key='block-nav'
      when={shouldBlockNavigation}
      message='Any cool message here'
    />
]

我的页面中有一个“取消”按钮,所以我想在单击此按钮后显示相同的提示,有人知道我该怎么做吗?

像这样的东西应该可以工作

   <Prompt
     key='block-nav'
     when={this.state.shouldBlockNavigation}
     message='Any cool message here'
  />
  <button onClick={(e) => {
      e.preventDefault();
      this.setState({shouldBlockNavigation:true})
     }}>
   CANCEL
 </button>

因此,只要其值为真且导航页面时,就会触发提示。

    <Prompt
      key='block-nav'
      when={this.state.shouldBlockNavigation}
      message='Any cool message here'
    />

按钮代码:

<button
  onClick={ () => {
    this.setState({shouldBlockNavigation:true});
    window.history.back();
  }
>
Cancel
</button>

所以每当有人点击取消按钮时,我们都会设置 when 属性 的值并强制导航。

希望对您有所帮助。