我正在尝试编写一个实用程序函数来获取当前组件(路由的(title
属性。
我可以获取路线的瓦片属性:
function getPageTitleByRoutes(routes) {
for (let i = routes.length - 1; i >= 0; i -= 1) {
if (routes[i].hasOwnProperty('title')) {
return routes[i].title;
}
}
return null;
}
但是现在我想将标题道具移动到我的组件:
function getPageTitle(props) {
// ?? Iterate recurively ?? Context ok on render ??
React.Children.forEach(props.children, (child, i) => {
console.log(child + ' at index: ' + i);
// If it has title
// ??
// ??
if(title) return title;
return getPageTitle(child.props);
});
return null;
}
我在反应路由器下有一个这样的组件设置:
<Router>
<Route path="/" title="App Title" component={App}>
<Route path="page1" title="Comp A" component={Comp1} />
<Route path="page2" title="Comp B" component={Comp2} />
</Route>
<Route path="/login" title="Login Comp" component={Login} />
</Router>
var NavBar = React.createClass({
render() {
const someTitle = getPageTitleByRoutes(this.props.routes);
// Line above works but now want to get 'title' (defaultProps)
// from "active/routed" component:
const someTitle = getPageTitle(this.props);
return (
<div>
<h2>{someTitle}</h2>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
然后我像这样创建我的应用程序:
var App = React.createClass({
render() {
return (
<div>
<NavBar />
{this.props.children}
</div>
)
}
});
也许还有另一种方法?我也连接了反应冗余...
您没有将任何道具或任何子项传递给<NavBar />
组件。 这就是为什么this.props.routes
和this.props.children
是空的。
试着给<NavBar />
一个路线道具和一些孩子。 您决定在那里添加什么。
例如:
<NavBar routes={[{title: 'First Title'}, {title: 'Second Title'}]} />
或者把你<App />
的孩子传给,就像你本来想的,但就像这样:
<NavBar>
{this.props.children}
</NavBar>