react-router 如何实现 vue-router 中 router-view 的功能

页面路由切换的时候,只有部分组件重新渲染,在 vue-router 中,可以通过 router-view 实现,
想问下在 react-router 中怎么实现。

阅读 10.1k
2 个回答

首先,版本是3还是4.

下面说下3的做法。

3里面route是可以嵌套的,如下

<route component={A}>
    <route path="/A/B" component={B}/>
    <route path="/A/C" component={C}/>
</route>

而A组件的写法通常如下

class A extends React.Component {
    render(){
        return (
            <div>{this.props.children}</div>
        )
    }
}

这里的children在不同路由下对应不同组件,即/A/C对应C组件,/A/B对应B组件。

也就是说,要变化的写在B、C组件内,不变化的写在A组件内。

正好搜索到这个解决方案,发现变化了很多,我补充一下

3 的写法为 如上那种,且 在组件中定义 <div>{this.props.children}</div>

4 为

<route element={<A />}>

<route path="/A/B" element={<B />}/>
<route path="/A/C" element={<C />}/>

</route>

且 需要在 A组件中

import { Outlet } from 'react-router-dom';
...
<div>

我是A组件
<Outlet />

</div>
...

来源:https://reactrouter.com/docs/...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进