同一布局路线上的动态子组件渲染

Dynimic child component rendering on same Layout Route

我有一个名为 Layout 的组件,它应该根据路由呈现不同的 child components。 父组件

export default class Layout extends Component{
    render(){
        return (
            <div>
                <div>
                    <div>
                        <Navbar/>
                        {this.props.sidebar}
                        {this.props.content}
                    </div>
                </div>
            </div>
        );
    }
}

在我的 main.jxs 中,我想使用 Layout component 渲染 3 Route,不同的 ChildComponent 作为侧边栏传递,内容道具如下:

<Route path="/profile" component={sidebar: <Sidebar />, content: <Content />} />
<Route path="/user" component={sidebar: <Sidebar />, content: <User />} />
<Route path="/edit" component={sidebar: <Sidebar />, content: <Edit />} />

组件也被导入。换句话说,我想根据路线动态更改布局的内容。我如何使用 react-router-dom 实现此目的?

如果我没看错你应该在 Route 组件中使用 render func 作为 prop (react router 4) 为了可以渲染多个组件。 参见 https://reacttraining.com/react-router/web/api/Route/render-func

另外我提供下一个小例子

https://jsfiddle.net/69z2wepo/85086/

你的做法是正确的,但你需要定义显示布局的索引路由,并且你的其他路由必须是子路由。

我将其用作

 <Route path="/" component={Layout} >
        <IndexRoute components={{ body: LandingPage }} />
        <Redirect from="appdetail/" to="/" />
        <Route path="appdetail/:applicationId" components={{ body: AppDetailPage }} />
 </Route>    

我的布局看起来像:

export class Layout extends React.Component<ILayoutProps, void> {

    /**
     * Renders this object.
     *
     * @return  A JSX.Element.
     */
    public render(): JSX.Element {

        const mainDivStyle: React.CSSProperties = {
            width: "100%",
            height: "100%",
            top: "0px",
            left: "0px",
            backgroundColor: "#f2f2f2",
            fontSize: "12px",
            fontFamily: "Gotham"
        };

        const contentDesktopStyle: React.CSSProperties = {
            height: "100%"
        };


        return (
            <div style={mainDivStyle}>
                    <div id="contentId" style={contentDesktopStyle}>
                        <Header />                        
                        { this.props.body }
                    </div>
            </div>
        );
    }
}