2016-04-01 74 views

回答

1

您可以檢查是否觸發的onblur點擊的DOM元素是按鈕或不是,是這樣的:你已經嘗試過

const ComponentA = React.createClass({ 
    propTypes: { 
     onBlur: React.PropTypes.func.isRequired, 
    }, 

    componentDidMount: function() { 
     document.addEventListener('click', this.onAnyClick); 
    }, 

    componentWillUnmount: function() { 
     document.removeEventListener('click', this.onAnyClick); 
    }, 

    onAnyClick(event) { 
     const container = this.refs.container; // DOM element 
     let isClickedOutside = true; // initialization 
     const eventTarget = event.target; // DOM element 
     let elem = eventTarget; 
     while (elem !== null) { 
      if (elem === container) { 
       isClickedOutside = false; 
       break; 
      } 
      elem = elem.offsetParent; 
     } 
     if (isClickedOutside) { 
      this.props.onBlur(eventTarget); 
     } 
    }, 

    render: function() { 
     return (
      <div ref="container"> 
       {/* component elements */} 
      </div> 
     ); 
    }, 
}); 

const Button = React.createClass({ 
    getElement: function() { // public method 
     return this.refs.element; // DOM element 
    }, 

    render: function() { 
     return (
      <input ref="element" type="button" value="Click me" /> 
     ); 
    }, 
}); 

const ParentComponent = React.createClass({ 
    onComponentABlur(eventTarget) { 
     if (eventTarget === this.refs.button.getElement()) { 
      // do something if button was clicked 
     } else { 
      // do something else 
     } 
    }, 

    render: function() { 
     return (
      <div> 
       <ComponentA onBlur={this.onComponentABlur} /> 
       <Button ref="button" /> 
      </div> 
     ); 
    }, 
}); 
相關問題