孩子如何获得其父母的道具?例如,
父组件-footer.jsx:
import React from 'react';
import $ from 'jquery';
import NavItem from './nav-item';
class Footer extends React.Component
{
constructor(props) {
super(props);
this.state = {
publicUrl: null,
currentUrl: null,
navitems: [],
};
}
// Then fetch the data using $.getJSON():
componentDidMount() {
this.serverRequest = $.getJSON(this.props.source, function (result) {
this.setState({
currentUrl: window.location.href,
publicUrl: result.publicUrl,
navitems: result.nav
});
}.bind(this));
}
componentWillUnmount() {
this.serverRequest.abort();
}
render() {
var loop = this.state.navitems.map(function(item, index){
return <NavItem key={index} item={item}></NavItem>;
});
return (
<div>
<div className="nav">
<ul>{ loop }</ul>
<p>{this.state.publicUrl}</p>
<p>{this.state.currentUrl}</p>
</div>
</div>
)
}
}
export { Footer as default }
子组件-nav-item.jsx:
从'react'导入React;
class NavItem extends React.Component
{
constructor(props) {
super(props);
}
render() {
return <li><a href={this.props.publicUrl + '/' + this.props.item.url}>{this.props.item.title}</a></li>
}
}
export { NavItem as default }
结果footer.jsx
(父):
this.props.publicUrl // http://my-website.com
结果nav-item.jsx
(子):
this.props.publicUrl // undefined but it should be http://my-website.com
有任何想法吗?
样本数据:
{
"publicUrl": "http:\/\/my-website.com",
"nav": [{
"navId": "3",
"title": "Home
"code": "home
"href": null,
"style": null,
"sort": "3",
"url": "home
"parentId": null,
"totalChildren": "0",
"createdOn": null,
"updatedOn": null
}, {
"navId": "4",
"title": "About
"code": "about
"href": null,
"style": null,
"sort": "4",
"url": "about
"parentId": null,
"totalChildren": "0",
"createdOn": null,
"updatedOn": null
}, {
"navId": "5",
"title": "Contact",
"code": "contact",
"href": "#contact",
"style": null,
"sort": "5",
"url": "contact",
"parentId": null,
"totalChildren": "0",
"createdOn": null,
"updatedOn": null
}]
}
我必须绑定this
到循环:
var loop = this.state.navitems.map(function(item, index){
return <NavItem key={index} publicUrl={this.state.publicUrl} item={item}></NavItem>;
}.bind(this));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句