我在名为 router.js 的文件中具有 routerTest()函数,该文件具有一些需要呈现的HTML。
class Router extends Component {
// Component constructor
constructor (props) {
// Call parent constructor
super(props)
// Set initial component state
this.state = {
line_of_business: 'Auto',
displayingDropdown: true,
open: false
}
}
static routerTest () {
return (
<div>
<Route exact path={paths.HOMEPAGE_PATH} render={() => (<Homepage {...this.state} />)} />
<Route exact path={paths.GROUPS_PAGE_PATH} render={routeProps => (<GroupsPage {...routeProps} {...this.state} />)} />
<Route exact path={paths.PROJECTS_PAGE_PATH} render={() => (<ProjectsPage {...this.state} />)} />
<Route exact path={paths.METAGROUP_PAGE_PATH} render={routeProps => <MetagroupPage {...routeProps} {...this.state} />} />
<Route path={paths.GROUP_PAGE_PATH} render={routeProps => (<GroupPage {...routeProps} {...this.state} />)} />
<Route path={paths.PROJECT_PAGE_PATH} render={routeProps => (<ProjectPage {...routeProps} {...this.state} />)} />
<Route exact path={paths.FAQS_PAGE_PATH} render={() => (<FAQSPage {...this.state} />)} />
<Route exact path={paths.ABOUT_PAGE_PATH} render={() => (<AboutPage {...this.state} />)} />
</div>
)
}
}
export default Router
在我想调用此函数的其他类中,我使用以下语句导入了该类:从'./router.js'导入Router。在其他类的呈现功能中,我具有以下代码:
// Render function
render () {
return (
<React.Fragment>
<BrowserRouter>
<div>
<NavigationBar {...this.state} handleChange={this.handleChange} setVisibility={this.setVisibility} openSearchBar={this.openSearchBar} />
{Router.routerTest()}
</div>
</BrowserRouter>
</React.Fragment>
)
}
我如何进行这项工作?我要做的就是调制我的代码,以便可以在另一个类中调用Router类中的内容。我需要两个类,否则 this.state 的内容将无法正常工作。
答案 0 :(得分:3)
要拥有良好的项目结构,请创建一个辅助函数helpers.jsx。
并像这样导出函数。
export default function routerTest () {
return (
<div>
<Route exact path={paths.HOMEPAGE_PATH} render={() => (<Homepage {...this.state} />)} />
<Route exact path={paths.GROUPS_PAGE_PATH} render={routeProps => (<GroupsPage {...routeProps} {...this.state} />)} />
<Route exact path={paths.PROJECTS_PAGE_PATH} render={() => (<ProjectsPage {...this.state} />)} />
<Route exact path={paths.METAGROUP_PAGE_PATH} render={routeProps => <MetagroupPage {...routeProps} {...this.state} />} />
<Route path={paths.GROUP_PAGE_PATH} render={routeProps => (<GroupPage {...routeProps} {...this.state} />)} />
<Route path={paths.PROJECT_PAGE_PATH} render={routeProps => (<ProjectPage {...routeProps} {...this.state} />)} />
<Route exact path={paths.FAQS_PAGE_PATH} render={() => (<FAQSPage {...this.state} />)} />
<Route exact path={paths.ABOUT_PAGE_PATH} render={() => (<AboutPage {...this.state} />)} />
</div>
)
}
}
并通过
在其他组件中调用它import { routerTest } from ./helpers`