我正在使用React,MobX状态树和react-router创建一个简单的网站。
基本上,网站的每个页面(Page1,Page2和Page3)必须包含一个针对台式机和移动设备的菜单。
这是我的结构:
index.tsx:
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'mobx-react'
import { Router } from 'react-router'
import { State } from './states'
import { Routes } from './Routes'
import { history } from './states/index'
function renderApp() {
ReactDOM.render(
<Provider state={State}>
<Router history={history}>
<Routes />
</Router>
</Provider>,
document.getElementById('root')
)
}
Routes.tsx是:
function About() {
return <h2>About</h2>
}
function RedirectToHomepage() {
return <Redirect to="/" />
}
function withHeader(Component: React.ComponentClass) {
return class withHeader extends React.Component {
render() {
return (
<div className="flex flex-column w-100 h-100">
<Header />
<Component />
</div>
)
}
}
}
@inject('state')
@observer
class WithMenu extends React.Component<IStateable> {
menuWidth = () => {
const { ui } = this.props.state
if (ui.isSmallDevice) {
return ui.isMenuOpen ? 'w-100 h-100' : 'w0 h0'
} else {
return 'w-20 min-w5 max-w6 h-100'
}
}
render() {
const { children } = this.props
const { ui } = this.props.state
const menuWidth = this.menuWidth()
const showMenu = ui.isDesktop || ui.isMenuOpen
return (
<div className={`w-100 h-100 flex`}>
{showMenu && <Menu className={`${menuWidth}`} />}
{!showMenu && <div className={`flex-auto`}>{children}</div>}
</div>
)
}
}
export function Routes() {
return (
<Switch>
<Route path="/" exact component={withHeader(Homepage)} />
<Route path="/about" exact component={About} />
<Route path={path} exact component={withHeader(Page1)} />
<Route path={path} exact component={withHeader(Page2)} />
<Route path={path} exact component={withHeader(Page3)} />
<Route component={RedirectToHomepage} />
</Switch>
)
}
我想要的是带有标题和菜单的Page1,Page2和Page3。
因此,可以构建一个可以像component={withHeaderAndMenu(Page1)}
这样调用的函数吗?
我不想重复每个组件内WithMenu
类中的逻辑。
我尝试放在这里:
function renderApp() {
ReactDOM.render(
<WithMenu>
<Provider state={State}>
<Router history={history}>
<Routes />
</Router>
</Provider>
</WithMenu>
document.getElementById('root')
)
}
但是我没有路由器。
我需要帮助。非常感谢
答案 0 :(得分:0)
考虑一下:
function withHeaderAndMenu(Component: React.ComponentClass) {
return class WithHeaderAndMenu extends React.Component {
render() {
return (
<div className="flex flex-column w-100 h-100">
<Header />
<WithMenu />
<Component />
</div>
)
}
}
}
并且:
<Route path={path} exact component={withHeaderAndMenu(Page1)} />
<Route path={path} exact component={withHeaderAndMenu(Page2)} />
<Route path={path} exact component={withHeaderAndMenu(Page3)} />