我创建了一个包含3个页面的应用程序,Home、Reptiles和Map。
我的问题出现在Reptiles和Map页面上。在爬行动物页面上,我显示了一系列物种列表,每个列表都有一系列分布国家和一个“查看地图”链接。当用户点击一个国家时,我希望地图页面显示选定的国家高亮显示(目前还没有实现,所以我只想将该国家传递到地图页面)。
当用户点击某个物种的“查看地图”时,我希望地图页面显示该物种的所有分布国家都被突出显示。目前,我可以在react-router的路由中传入reptile和country属性,但是当我尝试直接在Reptlie.js文件中的链接中传递属性时,我会收到错误警告:Unknown prop reptile on tag。从元素中删除此属性。有人能帮我解决如何直接向组件中的链接传递props的问题吗?还有,你如何生成动态URL?例如,map/species1或map/country1?
我认为我的问题在于Reptiles.js。使用的react-router版本是3.0.2。
下面是我的结构:
下面是我的代码:
router.js:
const routes = (
<Router history={browserHistory}>
<Route component={App}>
<Route path="/" component={Home}/>
<Route path="reptiles" name="reptiles" component={Reptiles}/>
<Route path="map" name="map" component={Map} country="Taiwan" reptile="Beardy"/>
</Route>
</Router>
);
export default routes;
App.js:
class App extends Component {
render() {
return (
<div className="container">
<header>
<span className="icn-logo"><i className="material-icons">code</i></span>
<ul className="main-nav">
<li><NavLink to="/">Home</NavLink></li>
<li><NavLink to="/reptiles">Reptiles</NavLink></li>
<li><NavLink to="/map">Map</NavLink></li>
</ul>
</header>
{this.props.children}
</div>
);
}
}
export default App;
Reptiles.js:
const Reptiles = () => {
let reptiles = ReptileList.map((reptile) => {
return (
<li className="reptile" key={reptile.id} >
<img className="reptile-img" src={reptile.img_src} />
<h3>{reptile.name}</h3>
<h4> Range
<span className="seeMap">
<NavLink to="map" reptile={reptile.id}>
See Map Here
</NavLink>
</span>
</h4>
{reptile.range.map(function(country,index) {
// only add comma if it's not the last one
return <span key={country}><NavLink to="map" country={country}> {(index < reptile.range.length-1)? country+',' : country} </NavLink></span>
})
}
</li>
);
});
return (
<div className="main-content">
<h2>Reptiles</h2>
<ul className="group">
{reptiles}
</ul>
</div>
);
}
export default Reptiles;
Map.js
var Map = React.createClass({
render: function() {
return (
<div>
<h2>Country passed from props: {this.props.route.country} </h2>
<h2>Reptile passed from props: {this.props.route.reptile} </h2>
</div>
)
}
});
export default Map;