【发布时间】:2016-04-24 12:17:20
【问题描述】:
以下是我的代码。 app.js 是根文件,about.js 是一个只显示一些文本的文件,index.js 使用 react-router 处理所有路由。我想在 app.js 中渲染我的 about.js。如果我不在 app.js 中编写“this.props.children”,它不会呈现。
App.js - 渲染其中所有子组件的根文件。
"use strict";
import React from 'react';
import { Link } from 'react-router';
class App extends React.Component {
render() {
console.log(this.props.children)
return(
<div>
<h1>Hello !</h1>
<Link to="about">About</Link>
{this.props.children} **//Is this necessary?**
</div>
)
}
}
export default App;
关于.js
"use strict";
import React from 'react';
class About extends React.Component {
render() {
return(
<div>
<h1>About page!</h1>
</div>
)
}
}
export default About;
Index.js - 处理路由的文件
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router'
/*Require own custom files*/
import App from './app';
import About from './about';
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="about" component={About}/>
</Route>
</Router>
), document.getElementById('app'))
我正在使用 ecma6 在 React 0.14 中工作。 为了使用react-router,是否需要在根组件中写入“this.props.children”?如果是这样,为什么? 有没有其他方法可以实现 react-router?
【问题讨论】:
-
是的,必须的,不然怎么让Router渲染Routes?
-
无论你把
this.props.children放在哪里都是加载匹配url路径的组件的地方。 -
你需要告诉它在哪里渲染路由中指定的子路由。
this.props.children做到了。
标签: reactjs react-router