How to use a custom component with react-router route transitions?

前端 未结 5 1548
生来不讨喜
生来不讨喜 2021-02-08 11:25

The article Confirming Navigation explains how to use a browser confirmation box in your transition hook. Fine. But I want to use my own Dialog box. If I were to use the methods

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-08 12:03

    Posting my solution for intercept back button or even a route change. This works with React-router 2.8 or higher. Or even with withRouter

    import React, {PropTypes as T} from 'react';
    
    ...
    componentWillMount() {
            this.context.router.setRouteLeaveHook(this.props.route, this.routerWillLeaveCallback.bind(this));
        }
    
        routerWillLeaveCallback(nextLocation) {
            let showModal = this.state.unsavedChanges;
            if (showModal) {
                this.setState({
                    openUnsavedDialog: true,
                    unsavedResolveCallback: Promise.resolve
                });
                return false;
            }
            return true;
        }
    }
    
    
    YourComponent.contextTypes = {
        router: T.object.isRequired
    };
    

提交回复
热议问题