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

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

本文关键字:其他 组件 参数 何通过 props react-router      更新时间:2023-09-26

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

//start: extent of my knowledge

假设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>
}
})
当被调用时,

将呈现"今天的主题是天气!"

//end: extent of my knowledge

现在,我将用下面的代码片段来讲解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?在代码中,我没有看到上面"我的知识范围"部分所表达的习语,即在两个路由中都没有<Topic params = {this.state.topics} />。JSX或header.jsx。链接到完整的回购在这里。React-router文档说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-Router将遍历路由声明中的每个组件(Main, Topic),并在使用React.createElement方法创建组件时将以下props"传递"给每个组件。下面是传递给每个组件的所有道具:

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

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

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

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

基本上内部实现中的调用是这样的:

this.createElement(components[key], props)

这意味着react-router使用上面定义的道具来初始化每个元素(Main, Topic等),因此这解释了如何在Topic组件本身中访问this.props.params,它是由react-router传递的!