假设我有这样的嵌套组件:
<root /> <comp1 /> <comp2 /> <target id={this.props.id}> <div>click me</div>
我想让单击目标在根目录上运行一个功能:
//on root component this.action = function(id){}
我需要像在React教程示例中一样,手动在链中的每个组件上设置属性吗?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>
还是像普通DOM一样,有什么方法可以使事件冒泡?
您可以使用速记将道具传递给子组件
<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)}>click me</div>