【问题标题】:React Router how to setup transition on parent elementReact Router如何在父元素上设置过渡
【发布时间】:2017-05-16 23:41:49
【问题描述】:

我有一个简单的路由器配置:

<Router history={browserHistory}>
    <Route lang="en" path="en" component={App}>
        <Route path="*" component={PageFactory} />
    </Route>
    <Redirect from="*" to="/en/*" />
</Router>

主 App 组件有以下内容:

<div className="app">
    <Home />
    <Sidebar {...sidebarProps}>
        {this.props.children}
    </Sidebar>
</div>

因此,当您打开 React 应用程序时,Home 组件总是会打开。当我单击 Home 组件中的链接(例如 /en/pages/about-page)时,页面的内容会加载到 Sidebar 组件,而 Sidebar 会得到一个 prop isOpen(这就是 ...sidebarProps 的用途)。一切正常。当我单击链接时,侧边栏会打开,内容会显示覆盖等。但是,过渡不会动画。这是我的 CSS:

.sidebar {
    position: fixed;
    left: 0px;
    top: 0px;
    width: 100%;
    height: 100%;
    z-index: 200;
    visibility: hidden;
    background: rgba(0, 0, 0, 0.8);
    overflow: scroll;
    @include transition(visibility 0s linear 0.3s);
    &.is-open {
        visibility: visible;
        @include transition-delay(0s);
        .sidebar-content {
            @include transform(translateX(0));
        }
    }
}

Sidebar 中的 isOpen 属性将 is-open 类添加到 Sidebar 组件的根元素。这里是 Sidebar 组件供参考:

const Sidebar = props =>
    <aside className={`sidebar ${props.isOpen ? ' is-open' : ''}`}>
        <SidebarContent>{props.children}</SidebarContent>
    </aside>
;

为了测试是否是 React 问题,我在我的 App 组件中添加了如下按钮:

constructor(props) {
    super(props);
    this.enableSidebar = this.enableSidebar.bind(this);
    this.state = { isOpen: false };
}

enableSidebar() {
    this.setState({ isOpen: true });
}

render() {
    const sidebarProps = { isOpen: this.state.isOpen };
    return (
        <div className="app">
            <button onClick={this.enableSidebar}>Enable Sidebar</button>
            <Home />
            <Sidebar {...sidebarProps}>{this.props.children></Sidebar>
        </div>
    );
}

当我单击按钮时,侧边栏会顺利打开。是 React Router 在每次请求时完全重新加载页面,使每个页面都是静态页面,而不是创建动态应用程序。

如何改变这种行为?如何使 React Router 在路由更改时不重新加载所有组件?我在想也许我的结构有问题。如果您也认为是,您能建议我一个解决方案吗?

【问题讨论】:

    标签: css reactjs react-router


    【解决方案1】:

    我发现了问题。我不得不使用 React Router Link 组件而不是 HTML 锚元素。所以不要使用:

    <a href="/en/pages/about-page">About</a>
    

    我必须使用:

    <Link to="/en/pages/about-page">About</Link>
    

    【讨论】:

      猜你喜欢
      • 2017-08-16
      • 2013-07-12
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多