代码之家  ›  专栏  ›  技术社区  ›  broschb

具有嵌套反应组件的onMouse事件

  •  0
  • broschb  · 技术社区  · 8 年前

    我正在尝试构建一个React组件,当鼠标放在悬停的组件上时,它可以突出显示悬停的组件。我将有这些组件的嵌套版本,所以当鼠标在外部组件上时,我希望在外部组件及其所有子组件周围放置一个边框,但是一旦鼠标移动到子组件上,我只希望子组件及其子组件周围的边框,而不是父组件。

    我创建了一个简单的小提琴来突出这个问题。这是非常不一致的。有时它可以工作,但有时它会围绕两个组件或没有组件绘制边框。

    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>
    1 回复  |  直到 8 年前
        1
  •  1
  •   Adeel Imran    8 年前

    在你的 Hover 您的组件 mouseEnter

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

    基本上当两个事件发生碰撞时 bubbling event.stopPropagation() 在 MDN Docs