react-router是如何通过props传递参数给其他组件的?
How does react-router pass params to other components via props?
到目前为止,我对属性如何通过参数从一个组件传递到另一个组件的了解程度如下
//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
传递的!
- 使用react.js渲染其他组件内部的组件
- 如何根据其他组件中的事件更新组件URL
- 如何绑定'这'到react类之外的函数,后者是来自其他组件的回调
- Angular 2 ES6/7事件发射器更新其他组件
- React 在点击时渲染其他组件.ReactJS中的最优模式
- HTML图像&其他组件根据页面宽度调整大小
- 为什么Angular UI引导使用提供程序来处理模态和工具提示中的逻辑,而不在其他组件中
- 如何在ember js中以编程方式在其他组件/视图中添加组件或视图
- 从其他组件获取参数[React JS]
- Angular 2的Array Subject .next()不会调用其他组件的观察者
- 通过 链接呈现其他组件
- react-router是如何通过props传递参数给其他组件的?
- 从组件内部访问其他组件引用
- Primefaces防止其他组件渲染
- 我需要从Angular 2中的其他组件中获取公共方法
- 如何做:AngularJS服务或其他组件在模块加载时实例化
- 在React.js中,点击一个组件中的按钮不会改变其他组件中的值
- 更改组件的属性不会触发'更改'在其他组件上
- 如何访问或更新其他组件类angular2中的组件类变量
- Reactjs在其他组件之前呈现组件