gpt4 book ai didi

javascript - 通过 React-router 渲染子组件

转载 作者:行者123 更新时间:2023-11-29 10:31:36 25 4
gpt4 key购买 nike

所以我一直在努力处理这段代码。我有一个接受 child 作为 Prop 的组件,它应该是我托管的所有页面的基础。

基础.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;

我现在的问题是:是否有可能摆脱这些抽象 TestLoginTestBase

我的最终目标是拥有这样的东西:

<Route exact path="/" component={Base(HomePage)} /> ,也就是去掉抽象层,直接一行渲染。

提前致谢。

编辑:感谢 anuragasaurus,我可以实现我想要的。我也可以在类里面做吗?该类声明为 class LoginPage extends React.Component并且有一个 render()方法。

最佳答案

您可以使用render 内联显示您的组件,

<Route exact path="/" render={()=><Base child={HomePage} />} />
<Route exact path="/login" render={()=><Base child={LoginPage} />}/>

关于javascript - 通过 React-router 渲染子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com