从Routes获取属性
Get properties from Routes
我无法从<Route />
传递属性
这里有一些代码:
/app.jsx (主应用程序)
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, IndexRoute } from 'react-router'
import App from './components/app'
import Home from './components/home'
import About from './components/about'
render((
<Router>
<Route path="/" component={App}>
<IndexRoute component={Home} title="Home" />
<Route path="about" component={About} title="About" />
</Route>
</Router>
), document.getElementById('app'))
/组件/app.jsx
import React from 'react';
import Header from './template/header'
class App extends React.Component {
render() {
return (
<div>
<Header title={this.props.title} />
{this.props.children}
</div>
)
}
}
export default App
/components/template/header.jsx
import React from 'react'
class Header extends React.Component {
render() {
return (
<span>{this.props.title}</span>
)
}
}
export default Header
当我单击主页路由*时,我希望我的Header
组件显示Home
。
当我点击我的about路由时,我希望我的Header
组件显示About
。
此时,我的Header
组件没有显示任何内容。this.props.title
是我的App
组件中的undefined
。看起来您无法从<Route />
传递属性
有办法做到这一点吗?
或者还有别的办法吗?例如,您能从子元素(this.props.children.title
或类似的东西)中获得一些吗?
看起来路由注入了一个带有匹配路由列表的routes
属性。列表中的最后一条路线具有您指定的道具。看见http://codepen.io/anon/pen/obZzBa?editors=001
const routes = this.props.routes;
const lastRoute = routes[routes.length - 1];
const title = lastRoute.title;
我对使用这个有点犹豫,因为routes
没有记录在Injected Props中,所以我不知道它在版本更新中有多可靠。一个更简单的选择,虽然不那么清晰,是使用this.props.location.pathname
并维护一个标题查找表。
最好和最灵活的选择可能是样板文件重的选择,在那里你定义模板,然后在组件之间重用它:
class Template extends React.Component {
render() {
return (
<div>
<Header title={this.props.title} />
{this.props.children}
</div>
)
}
}
class About extends React.Component {
render() {
return (
<Template title="About">
Some Content
</div>
)
}
}
相关文章:
- 通过id和class属性获取元素
- 使用javascript从节点属性获取数组值
- 如何在jquery中通过自定义属性获取输入字段的值
- 通过特定的数据属性获取元素
- 如何使用js/jquery将数组中的数据属性获取到DOM上的h3中
- 在 GWT 中按属性获取 DOM 元素
- 将从元素的数据属性获取的字符串转换为 json
- 角度表达式从对象数组中的相等属性获取对象的属性
- 仅从背景图像属性获取 URL
- 通过 Javascript 从 href 属性获取查询字符串
- 如何使用事件触发器和自定义属性获取元素的子元素
- jQuery从标题属性获取动态生成的内容
- 单击时从数据属性获取更新的值
- jQuery 从数据属性获取路径
- 使用属性获取对象值的运行时间
- 通过 src 属性获取元素,使用 javascript 而不是 jquery
- 如何从 href 属性获取默认 id 值
- 使用 javascript 按属性获取 iframe 的元素
- 使用 jQuery 按名称属性获取选择值
- 硒:借助链接等属性获取元素的路径