【问题标题】:Switch between components inside of an already routed component in react在反应中已路由组件内的组件之间切换
【发布时间】:2021-01-09 18:10:52
【问题描述】:

我使用 react-router 在导航栏的 2 个页面之间切换。其中一个页面是 Home 组件。现在我在主页中有 3 列作为组件。左列、中列和右列。通过左栏中的一个按钮,我想在首页中栏的两个组件之间进行切换。

function App() {
  return (
    <div className="App">
        <Router>
          <Navbar/>
          <Switch>

            <Route exact path="/">
              <Home/>
            </Route>
            <Route path="/FAQ">
              <FAQ/>
            </Route>

          </Switch>
        </Router>
    </div>
  );
}

家用组件->

class Home extends Component {
    render() {
        return (
                <div className={style.homeFlex}>
                    <LeftContainer/>

                    **<MidContainer/>**
                    **<AnotherMid/>**

                    <RightContainer/>
                </div>
            </div>
        )
    }
}

export default Home;

通过LeftContainer 内的按钮,我想在MidContainerAnotherMid 之间切换。

如何在从兄弟组件链接的已路由组件中使用路由器?如果除了使用路由器之外还有更好的方法来实现同样的效果,也请分享。

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

在这种情况下,您不需要路线。您可以使用状态来呈现 Home 组件中的不同组件。

假设您的 LeftContainer 组件如下所示:

class LeftContainer extends React.Component {
  render() {
    return (
      <div>
        <button onclick={() => this.props.handleSwitchComponent()}>
          click here to change component
        </button>
      </div>
    );
  }
}

你需要通过 props 传递一个函数,然后你可以像这样在Home 组件中使用这个组件:

class Home extends Component {
  state = { IsMidContainerVisible: true }

  handleSwitchComponent = () => {
    this.setState(({ IsMidContainerVisible }) => ({
      IsMidContainerVisible: !IsMidContainerVisible;
    }));
  };

  render() {
    return (
      <div className={style.homeFlex}>
        <LeftContainer handleSwitchComponent={this.handleSwitchComponent} />

        {/* Now here we need to specify when we want to show components */}
        {this.state.IsMidContainerVisible ? <MidContainer /> : <AnotherMid />}

        <RightContainer />
      </div>
    );
  }
}

export default Home;

【讨论】:

  • 非常感谢。这很有帮助。
猜你喜欢
  • 2015-12-18
  • 2019-12-07
  • 2018-09-10
  • 1970-01-01
  • 2017-10-18
  • 2017-12-07
  • 2019-04-04
  • 2018-06-17
相关资源
最近更新 更多