2015-08-16 15 views
6

Obecnie tworzę rozwijany przycisk, aby nauczyć się React. Zrobiłem dwa zdarzenia onMouseEnter i onMouseLeave w div jednostki nadrzędnej, aby były widoczne, gdy najechanie zniknie, gdy nie. Problem polega na tym, że te wydarzenia wiążą się tylko z rodzicem.W jaki sposób uczynićMouseLeave w React, należy uwzględnić kontekst podrzędny?

W jaki sposób uczynićMouseLeave w React, należy uwzględnić kontekst podrzędny? Lub, w jaki sposób sprawić, by stan rozwinął się, gdy wisiał na dzieciach?

class DropDownButton extends React.Component { 
constructor(){ 
    super(); 
    this.handleHoverOn = this.handleHoverOn.bind(this); 
    this.handleHoverOff = this.handleHoverOff.bind(this); 
    this.state = {expand: false}; 
} 

handleHoverOn(){ 
    if(this.props.hover){ 
     this.setState({expand: true}); 
    } 
} 

handleHoverOff(){ 
    if(this.props.hover){ 
     this.setState({expand: false}); 
    } 
} 

render() { 
    return (
     <div> 
      <div className={styles.listTitle} 
      onMouseEnter={this.handleHoverOn} 
      onMouseLeave={this.handleHoverOff}> 
      {this.props.name} 
      </div> 
      <div> 
      {React.Children.map(this.props.children, function(child){ 
      return React.cloneElement(child, {className: 'child'}); 
      })} 
      </div> 
     </div> 
    ); 
} 
} 

Odpowiedz

4

Masz dwie różne div w twoich DOM, które nie pokrywają się; Będę podzielić render więc jest to bardziej oczywiste:

render() { 
    return (
     <div> 

      <div className={styles.listTitle} 
       onMouseEnter={this.handleHoverOn} 
       onMouseLeave={this.handleHoverOff}> 
       {this.props.name} 
      </div> 

      <div> 
       {React.Children.map(this.props.children, function(child){ 
        return React.cloneElement(child, {className: 'child'}); 
       })} 
      </div> 

     </div> 
    ); 
} 

div że ma onMouseLeave z nim związane nie zawiera dzieci; tak więc, gdy mysz przesuwa się na dziecko, pozostawia wywołania div i this.handleHoverOff.

Można rozważyć zastosowanie CSS do ukrycia dzieci, czy nie powinny być wyświetlane, lub warunkowo nadadzą im:

render() { 
    return (
     <div className={styles.listTitle} 
      onMouseEnter={this.handleHoverOn} 
      onMouseLeave={this.handleHoverOff}> 
      {this.props.name} 
      {this.state.expanded && this.renderChildren()} 
     </div> 
    ); 
}, 

renderChildren() { 
    return (
     <div> 
      {React.Children.map(this.props.children, function(child){ 
       return React.cloneElement(child, {className: 'child'}); 
      })} 
     </div> 
    ); 
} 
+0

Działa. Zrobiłem głupi błąd, a rendering warunkowy jest dla mnie przydatny. Dzięki! –

Powiązane problemy