以下是我的代码。 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吗?
最佳答案
是的,需要有this.props.children。
在你的index.js中,你已经将你的路由定义为嵌套的。如果您在 / 中声明 about 路由,则必须将 about 页面呈现为 App 的子级。如果您不想在应用程序中调用 this.props.children ,请将它们分开相同级别的路由,但您将无法将其用作应用程序的一部分。
React 路由器基本上根据您的路由定义将“关于”组件作为子组件传递给应用程序。如果您不使用this.props.children,您将无法执行此操作。
如果您的应用程序中有其他页面,例如关于页面或索引页面。如果不使用 this.props.children,它们也不会渲染。
关于reactjs - React 0.14 - 使用react-router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34869771/