[React Router] Prevent Navigation with the React Router Prompt Component

In this lesson we'll show how to setup the Prompt component from React Router. We'll prompt with a static message, as well as a dynamic method with the message as a function. Finally we'll show that you can return true from the message as a function to dynamically allow navigation.

import React, { Component } from "react";
import { Prompt } from "react-router-dom";

class Profile extends Component {
  state = {
    name: "",
  };
  render() {
    return (
      <div>
        <Prompt
          when={!!this.state.name} <!-- Tell prompt should happen -->
          message={location => `Are you sure you want to go to ${location.pathname}`} <!-- if return string, then prompting, if return true, then allow-->
        />
        <div>
          <div>Nice looking profile! What's your name?</div>
          <input value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />
        </div>
      </div>
    );
  }
}

export default Profile;

原文地址:https://www.cnblogs.com/Answer1215/p/8721046.html