繁体   English   中英

如何通过链接和路线传递道具/状态-react.js

[英]How to pass props/state through Link and Route - react.js

我正在创建用react.js(create-react-app和react-router 3.0.2,没有redux)制作的第一个Web应用程序,我在通过链接和路由传递属性时遇到了问题(我不确定我要做的事情是否是“以实际方式”制作应用程序的正确方法)

想法是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 

此外,我很乐意接受有关任何重大错误或不良做法示例的信息。

您在这里有几种选择。 其中之一是使用路由参数。

1)首先,您需要更改path属性

 <Route path="addcost/:type" component={AddCost} /> 

2)在您的AddCost组件内部,您可以输入this.props.params.type并确定要呈现的内容

 class AddCost extends React.Component { render() { console.log(this.props.params.type) } } 

3)Finaly使用另一个to在你的链接属性

 <Link to="addcost/foo" /> <Link to="addcost/bar" /> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM