javascript-通过React-router渲染子组件
作者:互联网
所以我一直在努力与这段代码.我有一个接受儿童作为道具的组件,它应该是我托管的所有页面的基础.
Base.jsx:
import React from 'react';
import PropTypes from 'prop-types';
import { Link, NavLink } from 'react-router-dom';
const Base = ({ child }) => (
<div>
<div className="top-bar">
<div className="top-bar-left">
<NavLink to="/">React App</NavLink>
</div>
<div className="top-bar-right">
<Link to="/login">Log in</Link>
</div>
</div>
{child.render()} // HERE IS THE CHILD TO RENDER
</div>
);
Base.propTypes = {
child: PropTypes.object.isRequired
};
export default Base;
然后,在app.jsx中,ReactDom.render()所在的位置是:
import React from 'react';
import ReactDom from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import LoginPag from './components/LoginPag.jsx';
import Base from './components/Base.jsx';
import HomePage from './components/HomePage.jsx';
// for MaterialUI to work properly
injectTapEventPlugin();
const TestLogin = (props) => {
return (<Base child={LoginPag} />);
};
const TestBase = (props) => {
return(<Base child={HomePage}/>)
};
ReactDom.render((<BrowserRouter><MuiThemeProvider muiTheme={getMuiTheme()}>
<div>
<Switch>
<Route exact path="/" component={TestBase} />
<Route exact path="/login" component={TestLogin}/>
</Switch>
</div>
</MuiThemeProvider>
</BrowserRouter>), document.getElementById('react-app'));
最后,HomePage和LoginPag相似,这是HomePage.jsx:
import React from 'react';
import { Card, CardTitle } from 'material-ui/Card';
const HomePage = {
render() {
return (<Card className="container">
<CardTitle title="React Application" subtitle="This is the home page." />
</Card>);
}
};
export default HomePage;
我现在的问题是:是否有可能摆脱这些抽象TestLogin和TestBase?
我的最终目标是拥有这样的东西:
<路由精确路径=“ /” component = {Base(HomePage)} />就是说,摆脱抽象层并直接在一行中进行渲染.
提前致谢.
编辑:由于有甲龙,我可以实现我想要的.我也可以上课吗?该类被声明为LoginPage类扩展了React.Component并具有render()方法.
解决方法:
您可以使用render内联显示组件,
<Route exact path="/" render={()=><Base child={HomePage} />} />
<Route exact path="/login" render={()=><Base child={LoginPage} />}/>
标签:reactjs,react-router,javascript 来源: https://codeday.me/bug/20191111/2018378.html