我正在创建我的第一个使用react.js创建的Web应用程序(create-react-app和react-router 3.0.2,没有redux),我遇到了通过链接和路由传递属性的问题(我不确定我正在尝试做的是制作应用程序的“反应方式”的正确方法)
想法是AddCost组件(由于它不相关而不能粘贴)应根据传递给它的属性呈现一点点不同 . 但是我不知道该怎么做(如果它甚至可能那样)
Index.js是主要的渲染组件,App.js是主要的容器,而className ='content'的div是我希望和可互换呈现的地方(当我在{}中的一个链接上叮当作响时我希望渲染在之前呈现的相同位置(并且可以正常工作)但是我无法将支柱传递给组件,具体取决于我点击的哪个链接
所以主要问题是 Headers ,当使用react-router进行路由时,如何将信息从传递到?
//Index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App'
import Home from './components/Home'
import Stats from './components/Stats'
import Account from './components/Account'
import AddCost from './components/AddCost'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import './index.css'
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/AddCost" component={() => (<AddCost costType="value" />)}/>
<Route path="/stats" component={Stats} />
<Route path="/account" component={Account} />
</Route>
</Router>,
document.getElementById('root')
)
//App.js
import React, { Component } from 'react'
import './App.css'
import Header from './Header'
class App extends Component {
constructor(props) {
super(props)
this.state = {
costType: null
}
}
render() {
return (
<div className='App'>
<Header />
<div className="content">
{this.props.children}
</div>
</div>
)
}
}
export default App
//Home.js
import React, { Component } from 'react'
import { Link } from 'react-router'
import './Home.css'
class Home extends Component {
render() {
const costTypes = [
{ text: 'Health', icon: 'fa fa-heart' },
{ text: 'Bills', icon: 'fa fa-home' },
{ text: 'Gas', icon: 'fa fa-car' },
{ text: 'Vacation', icon: 'fa fa-plane' },
{ text: 'Lunch', icon: 'fa fa-coffee' },
{ text: 'Groceries', icon: 'fa fa-shopping-cart' },
{ text: 'Leisure', icon: 'fa fa-glass' },
{ text: 'Leisure', icon: 'fa fa-glass' },
]
const listItems = costTypes.map((type, i) => (
<Link key={i} className='cost__element' to='/addcost'>
<i className={type.icon} aria-hidden="true"></i>
<h1>{type.text}</h1>
</Link>
))
return (
<section className='home'>
<ul className='costList'>{listItems}</ul>
</section>
)
}
}
export default Home
此外,我很乐意接受有关任何重大错误或不良做法示例的信息 .
1 回答
你有几个选择 . 其中之一是使用路线参数 .
1)首先,您需要更改路线的
path
属性2)在
AddCost
组件中,您可以输入this.props.params.type
类型并决定要渲染的内容3)最后在链接中使用另一个
to
属性