0

您好,我在自舉中實現了我自己的InputDropdown組件,以便爲用戶提供能力輸入項目或從篩選列表中選擇它。 它工作的很好,但爲了隱藏下拉單擊元素,我在FormControl上添加了onBlur事件,它與Dropdown中的onSelect事件衝突。下拉關閉更快然後選擇發生。 因此,我在onBlur處理程序中添加了setTimeout,現在它正在等待100ms,然後嘗試關閉Dropdown.Menu。 我可以這樣做,並沒有解決方案嗎? Full code on CodePen在react-bootstrap中點擊跳出下拉元素

class InputDrop extends React.Component { 
    constructor(props) { 
    super(props) 
    this.state = { 
     text: props.item?props.item.name: '', 
     open: false, 
     show: !!props.item 
    } 
    const methods = ['toggleDropdown', 'textChange', 'onSelect', 'onKeyUp', 'stopShow', 'onBlur'] 
    methods.forEach(methodName => this[methodName] = this[methodName].bind(this)) 
    } 
    toggleDropdown() { 
    if(this.state.text && this.state.open) return 
    if (!this.state.open) this.inputItem.focus() 
    this.setState({open: !this.state.open}) 
    } 
    onBlur() { 
    setTimeout(() => (this.state.open && 
         this.setState({open: false, text: ''})), 100) 
    } 
    onSelect(eventKey) { 
    const index = this.props.items.findIndex(item => item.id == eventKey) 
    const item = this.props.items[index] 
    this.setState({ 
     open: false, 
     text: item.name, 
     show: true, 
    }) 
    this.props.onResult(item) 
    } 


    render() { 
    if (this.state.show) return <Button onClick={this.stopShow}>{this.state.text}</Button> 
    const items = this.state.open ? this.filteredItems() : null 
    return (
     <Dropdown 
     onSelect={this.onSelect} 
     open = {this.state.open && items.length}> 
     <InputGroup> 
      <FormControl 
      type='text' 
      value={this.state.text} 
      onClick={this.toggleDropdown} 
      onKeyUp={this.onKeyUp} 
      onBlur={this.onBlur} 
      inputRef={ref => this.inputItem = ref} 
      onChange = {this.textChange}/> 
      <InputGroup.Addon onClick={this.toggleDropdown}> 
       <Glyphicon glyph="triangle-bottom" /> 
      </InputGroup.Addon> 
     </InputGroup> 
     <Dropdown.Menu> 
      {items && items.map((item, index) => (
      <MenuItem key={item.id} eventKey={item.id}> 
       {item.name} 
      </MenuItem> 
     ))} 
     </Dropdown.Menu> 
     </Dropdown> 
    ) 
    } 
} 

回答

0

嘗試在onSelect功能改變代碼:

this.setState({ 
    open: false, 
    text: item.name, 
    show: true, 
}) 

到:

this.setState({ 
     // open: false, 
     text: item.name, 
     show: true, 
    }, this.state.open && this.setState({open: false, text: ''})) 

和刪除您的onblur功能。

+0

我刪除了onBlur事件。現在InputDrop不會檢測外部下拉菜單中的點擊,並且在發生這種情況時不要關閉它。 [CodePen](https://codepen.io/TogusaRusso/pen/eREagv) –