react路由中如何向组件传参数呢

加入代码中有这样一个路由需要渲染;

render(
    <Router history = {browserHistory} >
    <route path ="/" component={App} >
        <IndexRoute  component={Home} />
        <route path ="/jianjie" component={jianjie} />
        <route path ="/yewu" component={yewu} />
        <route path ="/lianxi" component={lianxi} />
        <route path ="/about" component={About} />
        <route path ="/test" component={test} />
    </route>
</Router>, ele)

但是App组件是这样的;

import React ,{ Component }from 'react';
import Nav from './nav';
import Foot from './foot';

class App extends Component{
    constructor(props){
        super(props);
    }
    render(){
        return (
            <div>
                {this.props.name}
                <Nav />
                {this.props.children}
                <Foot />
            </div>
        )
    }
}
export default App;

App组件中这个 {this.props.name}是通过外面参数传递进来的,但是上面的代码中怎么向App传递参数呢;

如果是单纯的渲染App可以这样写:

render(
    <App {...props}/>, ele)

希望有知道的朋友帮忙解答一下啊

阅读 18.9k
4 个回答

讲道理。react-router 封装的这些组件,是不允许你自定义传props的。只支持那几个固定的,比如history,
params,location,route等等,都是跟路径参数有关的。
如果想传一些自定义的数据,可以结合redux,直接connect往组件里传store。。
因为你直接给Router或者Route穿props 其实是给了Router组件,它不会帮你做注入props。
可以自己尝试封装一层。- -
还是用react-redux吧...

如果你用了react-router的话
在配置路由路径的时候可以这样写path=yourroutername/:id

在你的组件里就可以这样调用

const { location,params } = this.props;
console.log(params)  //这个就是你需要的参数  `typeof params` =`object`

我上面写的我需要的id就可以这样获得let myId=this.props.params.id 这个id的名字和上面path是对应的


    <route path ="/" render={()=><App name={输入参数} />} >

是路由向组件传参吗?
<Route path="/job/:id" component={jobDetail} />
jobDetail组件就能渠道路由中的ID了,通过this.props.params.id
可以参考下阮一峰的React Router,http://www.ruanyifeng.com/blo...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题