【问题标题】:Single application appbar to show back button when navigating throughout the application在整个应用程序中导航时显示返回按钮的单个应用程序应用栏
【发布时间】:2019-03-06 23:53:51
【问题描述】:

我的 app.js 文件如下所示:

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>
    );
  }
}

这个组件有一个 appbar 和一个带有路由的路由。 appbar 在这里的意义在于,应用程序在整个应用程序中始终只有一个 appbar。只有下面的页面会改变。

在我的联系页面中,我有一个按钮可以转到自定义页面,并传递了一个参数:

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

当应用程序转到此客户页面时,我希望应用栏显示一个后退按钮。所以我必须以某种方式通知 appbar 以显示此按钮,然后还要知道要返回哪个页面(它应该是最后一页)。我搜索了一些示例,但找不到适合这种情况的示例。

【问题讨论】:

  • 您还需要history.back()以外的东西吗?
  • @estus 我不这么认为。我只需要它回到他们来自的页面。我的问题是如何通知它在子页面上的应用栏,以便后退按钮出现,以及如何在按下后退按钮时知道它应该转到哪个页面。我还应该注意,我对反应和反应路由器很陌生,所以我可能会遗漏一些明显的东西。
  • 使用 app.js 中的状态来显示/隐藏传递事件以将按钮显示到联系我们页面并从那里处理。
  • @Justcode 所以 appbar 是父组件,那么它怎么知道它在哪个页面上呢?阅读反应路由器文档,例如,this.props.location.pathname 仅对子组件可用,并且根据文档不建议在子组件之间传递数据。然后我的问题似乎是如何通知父组件它在哪个页面上,并告诉父级它在哪个页面上
  • 你在哪里看到不推荐传球的道具?您将如何通知家长有关更改并告诉显示按钮?

标签: reactjs react-router material-ui


【解决方案1】:

React router 包含withRouter higher-order component,可以为应用栏组件提供相关的props。

React 路由器由 history.js 库提供支持,该库是浏览器历史 API 的抽象。虽然它可用于使用 history.goBack() 浏览浏览器历史记录,但它不能很好地用于单独浏览应用程序,因为窗口历史记录可能包含其他网站。

组件看起来像这样(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>}
      </>
    );
  }
}

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

【讨论】:

    猜你喜欢
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多