繁体   English   中英

react-router如何通过props将params传递给其他组件?

[英]How does react-router pass params to other components via props?

到目前为止,我对属性如何通过参数从一个组件传递到另一个组件的知识程度如下

//开始:我的知识范围

假设在A.jsx中存在一些名为topic状态变量。 我想把它传递给B.jsx,所以我执行以下操作

B = require('./B.jsx')
getInitialState: function() {return {topic: "Weather"}}
<B params = {this.state.topic}>

在B.jsx中,我可以做类似的事情

module.exports = React.createClass({
render: function() {
   return <div><h2>Today's topic is {this.props.params}!</h2></div>
}
})

在被召唤时将呈现“今天的主题是天气!”

//结束:我的知识范围

现在,我将通过以下代码片段阅读react-router教程

topic.jsx:

module.exports = React.createClass({
  render: function() {
    return <div><h2>I am a topic with ID {this.props.params.id}</h2></div>
    }
  })

routes.jsx:

var Topic = require('./components/topic');
module.exports = (
  <Router history={new HashHistory}>
    <Route path="/" component={Main}>
      <Route path = "topics/:id" component={Topic}></Route>
    </Route>

  </Router>
)

header.jsx:

  renderTopics: function() {
    return this.state.topics.map(function(topic) {
      return <li key = {topic.id} onClick={this.handleItemClick}>
        <Link to={"topics/" + topic.id}>{topic.name}</Link>
      </li>
    })
  }

其中this.state.topics是通过Reflux从imgur API中提取的主题列表。

我的问题是 :通过什么机制将params传递给topic.jsx的props 我在代码中没有看到上面关于“我的知识范围”的部分所表达的成语。 routes.jsx或<Topic params = {this.state.topics} />没有<Topic params = {this.state.topics} /> 链接到这里完整回购 React-router docs说params是“ 从原始URL的路径名解析出来的 ”。 这并没有引起我的共鸣。

这是一个关于react-router内部的问题。

react-router本身就是一个React组件,它使用props以递归方式将所有路由信息传递给子组件。 但是,这是react-router一个实现细节,我知道它可能会令人困惑,所以继续阅读更多细节。

您的示例中的路由声明是:

<Router history={new HashHistory}>
  <Route path="/" component={Main}>
    <Route path = "topics/:id" component={Topic}></Route>
  </Route>
</Router>

基本上,当使用React.createElement方法创建组件时,React-Router将遍历路由声明中的每个组件(Main,Topic)并将以下props传递给每个组件。 以下是传递给每个组件的所有道具:

const props = {
   history,
   location,
   params,
   route,
   routeParams,
   routes
}

props值由react-router的不同部分使用各种机制计算(例如,使用正则表达式从URL字符串中提取数据)。

React.createElement方法本身允许react-router创建一个元素并传递上面的props。 方法的签名:

ReactElement createElement(
  string/ReactClass type,
  [object props],
  [children ...]
)

所以基本上内部实现中的调用看起来像:

this.createElement(components[key], props)

这意味着react-router使用上面定义的props来启动每个元素(Main,Topic等),这样就解释了如何在Topic组件中访问this.props.params ,它是通过react-router传递的!

暂无
暂无

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

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