以下是我的代码 . 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;
About.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?
4 回答
Yes ,需要有this.props.children .
在index.js中,您已将路由定义为嵌套 . 如果在 / 中声明 about 路由,则必须将该页面呈现为App的子级 . 如果你不想在App中调用this.props.children然后将它们分成相同级别的路由,但你将失去将它作为App的一部分使用的能力 .
React路由器基本上将About组件作为子组件传递给App,这取决于您对路由的定义 . 如果你不使用this.props.children就不能这样做 .
如果您的应用程序中有其他页面,如页面或索引页面 . 他们也不会在不使用this.props.children的情况下渲染 .
是的,您需要使用app.js文件中的来显示子路由页面 . 因为您设置app.js是路径路径=“/”中的索引路由 . 它将在主页中显示app.js数据,当您导航到下一个子页面时,它还会在同一页面中显示app.js数据和子页面数据 . 当您想要重用诸如Header导航菜单之类的组件以在所有页面中显示相同的 Headers 而不重新创建 Headers 组件时,它将非常有用 .
this.props.children
是React在包含该组件子项的组件上自动设置的属性 . 您可以在不放置this.props.children
的情况下使用react-router .在您的情况下,App.js组件中的
this.props.children
对应于放在应用程序中<App />
标记内的内容 . 如果没有<App />
标记,则不会放入任何子项,只会生成App.js中的渲染 .以下是使用ReactSpeed.com的嵌套路由的完整示例 .
HomePage component渲染
props.children
也列在GitHub上 . 路线在index.jsx
中定义,可在GitHub here上找到 . 所有嵌套组件也列在GitHub上 .