【学习笔记】喵生第一个React插件=>AinuReactRoutesRender.js
以往我一直是Vue的爱好者。
作为一个努力像全栈进发的前端开发者,除了Vue,React还是有必要攻占的。
我对于React一直是有着浓厚的兴趣。
只是一直没时间研究而已。。。。
哎。。。。。
介于我目前依然在React开发踩坑学习中。
说是新手也不为过。
所以React大佬见到此文章无视即可。
这仅仅只是我今日学习成果之展示耳。
废话不多说了。原因也不多说了。直接上代码!
笔记仅适用于React Hooks。
今日主要研究的对象是React如何渲染组件包裹内容、如何使用子路由。
如何渲染组件包裹的子内容?
我有一个布局组件,名叫:Layout
如此段代码:
<Layout>
<div>这是Layout布局页面</div>
</Layout>
如果我想实现将组件包裹的div渲染出来、我的组件内部该怎么写?
import React, { useState, useEffect } from 'react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import routes from '../route/index'
function Layout({ children }, props) {
return (
<div className='mainDiv'>
<div className='leftNav'>
<div className='rightMain'>
{React.Children.toArray(children).map((child, index) => {
return child
})}
</div>
</div>
)
}
export default Layout
通过此段代码即可实现渲染组件包裹的内容。
如何实现子路由?
这个东西也是踩坑了许久。真乃痛苦也!
直接上代码吧。
routes.map((route, key) => {
return (
<Route
key={key + route}
path={route.path}
// 有子路由的情况下不能有exact
// 是否乃是精准路由地址
exact={route.exact}
render={(props) => (
// pass the sub-routes down to keep nesting
<route.component
{...props}
Layout={route.layout}
routes={route.children}
>
{routes.children.map((route, key) => {
return (
<Route
key={key + route}
path={route.path}
// 有子路由的情况下不能有exact
// 是否乃是精准路由地址
exact={route.exact}
render={(props) => (
// pass the sub-routes down to keep nesting
<route.component
{...props}
Layout={route.layout}
routes={route.children}
>
{/* 可无限递归 */}
</route.component>
)}
// component={route.component}
></Route>
)
})}
</route.component>
)}
// component={route.component}
></Route>
)
})
这2个问题真的是踩的我很费劲。
我不就是为了实现Layout布局吗。。。
源自新手废物的痛哭流涕555哭泣中。。。
AinuReactRoutesRender插件
通过以上2种方式,即可通过设置路由数组,以渲染所有根路由、子路由、Layout布局文件了。
此插件尚未完全体。仅初版耳。
目测后续根据对React的熟悉。肯定还会继续改进的。
/**
* React路由渲染插件
* 可嵌套渲染一切子路由的插件
*/
import React from 'react'
import {
BrowserRouter as Router,
Redirect,
Route,
Switch,
Link,
withRouter,
} from 'react-router-dom'
function renderRoutes(routes) {
console.log(routes)
return routes && routes.length
? routes.map((route, key) => {
return (
// <Switch key={key + route}>
<Route
key={key + route}
path={route.path}
// 有子路由的情况下不能有exact
// 是否乃是精准路由地址
exact={route.exact}
render={(props) =>
// pass the sub-routes down to keep nesting
route.layout ? (
<route.layout>
<route.component
{...props}
Layout={route.layout}
routes={route.children}
>
{renderRoutes(route.children)}
</route.component>
</route.layout>
) : (
<route.component
{...props}
Layout={route.layout}
routes={route.children}
>
{renderRoutes(route.children)}
</route.component>
)
}
// component={route.component}
></Route>
)
})
: ''
}
const RenderRoutes = (routes) => {
return <Router>{renderRoutes(routes)}</Router>
}
export default RenderRoutes
感谢您浪费了几分钟在我这里闲逛。
希望您在爱喵日记玩的开心哦~~~
(,,´•ω•)ノ"(´っω•`。)
日本千叶县
喵星人制造机器
like
dislike
1
899
comments0
ShiinaAiiko.NO.00004欢迎旅行者到此一游
推薦
從未發佈過哦