反应:事件冒泡通过嵌套组件 [英] React: event bubbling through nested components
本文介绍了反应:事件冒泡通过嵌套组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< root />
< comp1 />
< comp2 />
< target id = {this.props.id}>
< div>点击我< / div>
我想点击目标在root上运行一个功能:
//根组件
this.action = function(id){}
我需要在链中的每个组件上手动设置一个属性,如反应教程示例中? Jsfiddle
< root />
< comp1 clickHandler = {this.action} />
< comp2 clickHandler = {this.clickHandler} />
< target id = {this.props.id} clickHandler = {this.clickHandler} />
< div onClick = {this.props.clickHandler.bind(this,this.props.id)}>点击我< / div>
还是有一些方法来像正常的DOM一样将事件弹起来?
解决方案
您可以使用速记将道具传递给子组件
code>< Component {... this.props} more =values/>
所以在你的情况下:
< root />
< comp1 clickHandler = {this.action} />
< comp2 {... this.props} />
< target {... this.props} id = {this.props.id} />
< div onClick = {this.props.clickHandler.bind(this,this.props.id)}>点击我< / div>
Let's say I have nested components like this:
<root />
<comp1 />
<comp2 />
<target id={this.props.id}>
<div>click me</div>
I want to make clicking on target run a function on root:
//on root component
this.action = function(id){}
Do I need to do manually set a property on every component in the chain, like in the React tutorial example? Jsfiddle
<root />
<comp1 clickHandler={this.action}/>
<comp2 clickHandler={this.clickHandler}/>
<target id={this.props.id} clickHandler={this.clickHandler} />
<div onClick={this.props.clickHandler.bind(this, this.props.id)}>click me</div>
Or is there some way to bubble the events up like in normal DOM?
解决方案
You can use the shorthand to pass props through to child components
<Component {...this.props} more="values" />
So in your case:
<root />
<comp1 clickHandler={this.action}/>
<comp2 {...this.props} />
<target {...this.props} id={this.props.id} />
<div onClick={this.props.clickHandler.bind(this, this.props.id)}>click me</div>
这篇关于反应:事件冒泡通过嵌套组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文