2017-09-27 28 views
0

我創建了一個下拉菜單使用onFocus和onBlur。有一個原因,我不使用onClick,因爲onFocus和onBlur我不需要手動關閉菜單,如果我有多個下拉菜單。防止檢查checkbox上觸發Blur

class Dropdown extends React.Component { 
     constructor(props) { 
     super(props); 
     this.state = { 
     open: false 
     } 
    } 

    render() { 
     return(
     <div 
     tabIndex="1" 
     onFocus={() => this.setState({open: true})} 
     onBlur={() => this.setState({open: false})} 
     > 
     <p>Menu</p> 
     <div style={this.state.open === false ? {display: 'none'} : {display: 'block'} }> 
     {this.props.children} 
     </div> 
     </div> 
    ) 
    } 
} 

class App extends React.Component { 
    constructor(props) { 
     super(props); 

    } 

    render() { 
     return (
      <div> 
      <Dropdown> 
      <li onClick={() => alert('link 1')}>link 1</li> 
      <li onClick={() => alert('link 2')}>link 2</li> 
      <input type="checkbox" label="check"/> 
      </Dropdown> 
      </div> 
     ); 
    } 
} 

但問題是複選框將無法正常工作,因爲它會觸發onBlur。

演示http://jsfiddle.net/dL99rx27/

如何防止的onblur觸發,當我點擊複選框?我使用onClick它沒有這樣的問題。

回答

0

你有沒有嘗試改變下面的語句:

onBlur={() => this.setState({open: false})} 

onBlur={() => this.setState({open: true})} 
+0

然後演示如何關閉該對話框?我不認爲你理解我的問題。 –

0

檢查點擊的元素(用鼠標按下)是輸入,因爲輸入更改焦點。 這應該工作,我已經添加了一個名爲inpClick的狀態的新屬性,當單擊組件中的輸入時該屬性將變爲true。

入住這裏

http://jsfiddle.net/prabushitha/ed9yxun9/1/

class Dropdown extends React.Component { 
     constructor(props) { 
     super(props); 
     this.state = {open: false, inpClick:false}; 
    } 

    render() { 
     return(
     <div 
     tabIndex="1" 
     onFocus={() => this.setState({open: true})} 
     onBlur={() => { 
      if(!this.state.inpClick){ 
      this.setState({open: false}); 
      }else{ 
      this.setState({inpClick: false}); 
      } 
      } 
     } 

      onMouseDown={(e)=>{ 
      if(e.target.nodeName=="INPUT"){ 
       this.setState({inpClick: true}); 
      } 
      } 
      } 
     > 
     <p>Menu</p> 
     <div style={this.state.open === false ? {display: 'none'} : {display: 'block'} }> 
     {this.props.children} 
     </div> 
     </div> 
    ) 
    } 
} 

class App extends React.Component { 
    constructor(props) { 
     super(props); 

    } 

    render() { 
     return (
      <div> 
      <Dropdown> 
      <div> 
      <li onClick={() => alert('link 1')}>link 1</li> 
      <li onClick={() => alert('link 2')}>link 2</li> 
      <input type="checkbox" label="check" /> 
      <li onClick={() => alert('link 2')}>link 2</li> 
      </div> 
      </Dropdown> 
      </div> 
     ); 
    } 
} 

React.render(<App />, document.body);