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

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>
}
})

调用时将呈现 "Today's topic is Weather!"

//结尾:我的知识范围

现在,我将通过以下代码片段学习有关 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 通过什么机制传递给 props 用于 topic.jsx?在代码的任何地方,我都没有看到在 "extent of my knowledge" 即上一节中表达的成语。 routes.jsx 或 header.jsx 中都没有 <Topic params = {this.state.topics} />。 Link 到 full repo here. React-router docs says that params is "parsed out of the original URL's pathname”。这并没有引起我的共鸣。

这是一个关于 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-Router 将遍历路由声明中的每个组件(Main,Topic)和 "pass" 在使用 [= 创建组件时,每个组件的以下道具18=] 方法。以下是传递给每个组件的所有道具:

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

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

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

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

所以基本上内部实现中的调用如下所示:

this.createElement(components[key], props)

这意味着 react-router 使用上面定义的属性来启动每个元素(主要、主题等),这样就解释了如何在 [=24= 中访问 this.props.params ] 组件本身,它由 react-router!

传递