React Router - How to achieve tab-like navigation?

2019-03-19 21:20发布

问题:

I'm new to React and developing my first application using React. My application had a tab component with 4 tabs, and each tab's content was set up as a separate component. Now I'm replacing the tab with 4 different routes. So, I got rid of the tab and used react-router to set up 4 routes, one for each of the 4 components.

With tabs, the content of a tab would maintain its state when navigating to a different tab and coming back. For example, say the tab has a list and user has scrolled to the bottom of the list. If the user navigates to a different tab and comes back, the list would remain scrolled to the bottom. This is the desired behavior for my application.

However, I'm not able to achieve this behavior with routes. I noticed that when I navigate from one route to another, the components are re-instantiated (not just re-rendered). I can tell this because the constructor of the component is called every time the route for the component becomes active.

I want to achieve the tab-like behavior. I know that for Angular there's a UI-Router-Extras library that provides Deep State Redirect (for tab-like navigation). It works really well in my Angular project. But I can't find a similar option for React. I have tried react-router and react-router-component and both re-instantiate a component when its route becomes active.

Is there a solution to achieve tab-like behavior for the routes in React?

回答1:

Personally, I chose to ditch react-router in this case and create a parent component with a state containing the current tab to display, while only displaying the active one.

Here's a very simple example

    <div
      style={{display: this.state.currentTab === 'component_a' ? 'block' : 'none'}}
    >
      <ComponentA />
    </div>
    <div
      style={{display: this.state.currentTab === 'component_b' ? 'block' : 'none'}}
    >
      <ComponentB />
    </div>


回答2:

You have two options, use Redux, or show/hide components based on tabs.

Heres an example to show/hide components

{this.state.showAboutMe ? <AboutMeComponent navigation={this.props.navigation} props={this.props.user} /> : undefined}