小编典典

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

reactjs

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

//开始:我的知识范围

假设存在一些topic在A.jsx中调用的状态变量。我想将此传递给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>
    }
  })

route.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传递给propstopic.jsx?在代码中的任何地方都看不到上一节中“我的知识范围”即表达的习惯用语。<Topic params = {this.state.topics} />route.jsx或header.jsx中都没有。在这里链接到完整的仓库。React-router文档说,参数是“
从原始URL的路径名中解析出来的 ”。这没有引起我的共鸣。


阅读 472

收藏
2020-07-22

共1个答案

小编典典

那是一个关于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方法创建组件时将以下属性“传递”到每个组件。这是传递给每个组件的所有道具:

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使用上面定义的道具来初始化每个元素(主要,主题等),从而解释了如何this.props.paramsTopic组件本身中进行访问,它被传递了react- router

2020-07-22