代码之家  ›  专栏  ›  技术社区  ›  user2924127

在整个应用程序中导航时显示“后退”按钮的单个应用程序appbar

  •  0
  • user2924127  · 技术社区  · 7 年前

    class App extends Component {
      render() {
        const {classes} = this.props;
        return (
          <React.Fragment> 
            <AppBar/>
            <BrowserRouter>
              <Route render={({location}) => (
              <TransitionGroup>
              <CSSTransition
                  key={location.key}
                  timeout={100}
                  classNames="someanimation"
                >
              <Switch location={location}>
                   <Route exact path="/" component={HomePage} />
                   <Route exact path="/contact" component={ContactPage} />
                   <Route exact path="/customer/:id" component={CustomerPage} />
                   <Route component={ErrorPage} />
                 </Switch>
               </CSSTransition>
             </TransitionGroup>
           )} />
            </BrowserRouter>
         </React.Fragment>
        );
      }
    }
    

    在我的联系人页面中,我有一个按钮,它指向一个传递参数的自定义页面:

    <Button component={Link} to={'/customer/' + customerID[99]}>
    

    当应用程序转到这个客户页面时,我希望appbar显示一个back按钮。所以我必须通知appbar显示这个按钮,然后还要知道返回哪一页(应该是最后一页)。我在谷歌上搜索了一些例子,但找不到一个适合这个案子的。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Estus Flask    7 年前

    反应路由器包含 withRouter higher-order component 可以为应用程序提供相关的道具栏组件。

    history.js history.goBack() ,它无法单独在应用程序上导航,因为窗口历史记录可能包含其他网站。

    组件可以如下所示(a demo )并且应该是路由器组件的子级以获取路由器道具:

    @withRouter
    class AppBar extends Component {
      state = {
        locations: [this.props.location]
      };
    
      componentDidMount() {
        this.props.history.listen((location, action) => {
          if (action === 'REPLACE')
            return;
    
          this.setState({
            locations: [location, ...this.state.locations]
          })
        });
      }
    
      back = () => {
        const [location, ...locations] = this.state.locations;
        this.setState({ locations });
        this.props.history.replace(location);
      }
    
      render() {
        return (
          <>
            {this.state.locations.length > 1 && <button onClick={this.back}>Back</button>}
          </>
        );
      }
    }
    

    它跟踪位置的变化并在其中导航。将其与浏览器历史记录导航按钮(后退和前进)保持同步将是一项更为复杂的任务。

    推荐文章