简体   繁体   English

带有嵌套React组件的onMouse事件

[英]onMouse event with nested React components

I am trying to build a React component that allows highlighting the hovered component when the mouse is over it. 我正在尝试构建一个React组件,该组件允许在鼠标悬停在其上方时突出显示悬停的组件。 I will have nested versions of these components, so when the mouse is over the outer component I want to put a border around the outer component and all of its children, but once the mouse moves over a child component I only want the border around the child component and it's children, but not the parent component. 我将拥有这些组件的嵌套版本,因此当鼠标悬停在外部组件上方时,我想在外部组件及其所有子组件周围放置边框,但是一旦鼠标移到子组件上,我只希望在外部组件周围放置边框子组件及其子组件,但不是父组件。

I created a simple fiddle to highlight problem. 我创建了一个简单的小提琴来突出问题。 It is very inconsistent. 这是非常不一致的。 At times it works, but other times it draws the border around both components or none. 有时它会起作用,但有时它会在两个组件之间绘制边框,或者不在两个组件之间绘制边框。

 class Hello extends React.Component { render() { return <div> <Hover name={'Outer Component Hover'}> <Hover name={'Inner Component Hover'}/> </Hover> </div>; } } class Hover extends React.Component { constructor(props) { super(props); this.state = { draggable: false }; } mouseEnter = () => { this.setState({ draggable: true }); } mouseLeave = () => { this.setState({ draggable: false }); } render() { var cls = this.state.draggable ? 'over' :'none'; return ( <div className={cls} onMouseEnter={this.mouseEnter} onMouseOut={this.mouseLeave}> {this.props.name} {this.props.children} </div> ) } } ReactDOM.render( <Hello name="World" />, document.getElementById('container') ); 
 .over { border-width: 2px; border-style: solid; border-color: red; cursor: move; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"> <!-- This element's contents will be replaced with your component. --> </div> 

In your Hover component in your mouseEnter you need to use the event that is already being passed. 在你的Hover在组件mouseEnter你需要使用已经被传递的事件。 To stop event propagation 停止事件传播

mouseEnter = event => {
   event.stopPropagation();
   // do rest of the stuff as is
}

Basically when 2 event collide this called bubbling , you can rad more event.stopPropagation() in the MDN Docs 基本上,当2事件发生冲突(称为bubbling ,您可以在MDN文档中添加更多event.stopPropagation()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM