【发布时间】:2017-08-10 17:30:00
【问题描述】:
我正在创建我的第一个使用 react.js 制作的 Web 应用程序(create-react-app 和 react-router 3.0.2,没有 redux),我在通过链接和路由(我不确定我正在尝试做的是否是制作应用程序的“反应方式”的正确方法)
想法是 AddCost 组件(我没有粘贴,因为它无关紧要)应该根据传递给它的属性呈现一点不同。但是我不确定该怎么做(如果有可能的话)
Index.js 是主要的渲染组件,App.js 是主要的容器,而 className='content' 的 div 是我希望 {Home} 和 {AddCost} 交替渲染的地方(当我点击其中一个{Home} 中的链接我想将 {AddCost} 渲染在与 {Home} 之前渲染的相同位置(并且有效),但我无法将道具传递给 {AddCost} 组件,具体取决于我点击的链接)
所以主要问题如题所示,react-router 用于路由时,如何将信息从 {Home} 传递到 {AddCost}?
//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
此外,我很乐意接受有关任何重大错误或不良做法示例的信息。
【问题讨论】:
-
您应该将此发布到代码审查:codereview.stackexchange.com。 Stack Overflow 用于获取编程问题的答案,而不是获取有关如何改进代码的建议。
-
我知道 CE 但是我提供的代码不起作用,所以我实际上问了一个编程问题,即如何通过 LINK 和 Route 传递道具。我也考虑过 CE,但在我看来,只有工作代码应该在那里发布。
-
啊,好吧,我没有从你的帖子中意识到这一点。然后请对您的帖子提出实际问题(我没有找到任何问题)以及您收到的错误消息。
-
好的,我已经稍微编辑了我的帖子,以便更清楚我的问题到底是什么,但是我没有粘贴任何错误消息,因为我没有收到任何错误消息。
标签: javascript reactjs react-router