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

the*_*ero 30 javascript reactjs reactjs-flux react-router refluxjs

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

//开始:我的知识范围

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

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

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

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

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

//结束:我的知识范围

现在,我将通过以下代码片段阅读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>
    }
  })
Run Code Online (Sandbox Code Playgroud)

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>
)
Run Code Online (Sandbox Code Playgroud)

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>
    })
  }
Run Code Online (Sandbox Code Playgroud)

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

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

Far*_*ina 57

这是一个关于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>
Run Code Online (Sandbox Code Playgroud)

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

const props = {
   history,
   location,
   params,
   route,
   routeParams,
   routes
}
Run Code Online (Sandbox Code Playgroud)

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

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

ReactElement createElement(
  string/ReactClass type,
  [object props],
  [children ...]
)
Run Code Online (Sandbox Code Playgroud)

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

this.createElement(components[key], props)
Run Code Online (Sandbox Code Playgroud)

这意味着,react-router使用上面定义的道具,启动各项元素(主,主题等),让你解释如何能访问this.props.paramsTopic组件本身,它是过去了react-router!

  • 我刚刚完成了以下实现:https://github.com/rackt/react-router/tree/master/modules (7认同)
  • 谢谢你的回答.我总是很好奇如何挖掘这些东西.这是通过经验,还是你在文档中找到它?如果是这样,请指出我的确切位置? (2认同)