2017-08-04 27 views
1

不太確定如何做到這一點,在Redux-Form世界中頗爲新穎。我有一個自定義組件,用於顯示無序列表的onFocus事件以及隱藏它的onBlur事件。我也將一個onClick事件附加到這些項目上,因爲一旦我點擊了一個列表項目,但是點擊事件從不會因爲模糊首先觸發而觸發,我想更改輸入字段的值。 不知道我是否正確處理我的代碼。 這裏是我的自定義組件:處理Redux-form事件

import React, { Component } from 'react' 
import pageStyles from '../../../styles.scss' 

class MyInput extends Component { 

    constructor(props) { 
    super(props); 
    this.state = { 
     dropdownIsVisible: false, 
     dropdownCssClass: 'dropdown' 
    } 
    this.handleFocus = this.handleFocus.bind(this); 
    this.handleBlur = this.handleBlur.bind(this); 
    this.handleClick = this.handleClick.bind(this); 
    } 

    handleFocus() { 
    this.setState({ 
     dropdownIsVisible: true, 
     dropdownCssClass: ['dropdown', pageStyles.dropdown].join(' ') 
    }) 
    } 

    handleBlur() { 
    this.setState({ 
     dropdownIsVisible: false, 
     dropdownCssClass: 'dropdown' 
    }) 
    } 

    handleClick() { 
    console.log('here I am') 
    } 

    render() { 
    const { 
     input: { 
     name, 
     value, 
     onFocus 
     }, 
     label, 
     hasOptions, 
     options, 
     cssClass, 
     meta: { 
     touched, 
     error 
     } 
    } = this.props 

    if(options) { 
     var listItems = options.map((item) => 
     <li key={ item.id } onClick={ this.handleClick }>{ item.name }</li> 
    ) 
    } 

    return (
     <div className={ cssClass }> 
     <label>{ label }</label> 
     <input name={ name } id={ name } type="text" onFocus={ this.handleFocus } onBlur={ this.handleBlur } autoComplete="off" /> 
     { hasOptions === true ? <ul className={ this.state.dropdownCssClass }>{ listItems }</ul> : null } 
     { touched && error && <span className="error">{ error }</span> } 

     </div> 
    ) 
    } 
} 

export default MyInput 

回答

1

使用lodash debounce功能。此函數在函數調用之前添加了延遲,因此您可以在嵌套元素單擊的情況下將其取消。

添加在構造函數:

this.handleBlur = debounce(this.handleBlur, 100); 

更換​​:

handleClick() { 
    if(this.handleBlur.cancel){ 
    this.handleBlur.cancel() 
    } 
    console.log('here I am') 
} 
+0

謝謝,它的工作原理就像一個魅力。現在我必須弄清楚如何改變輸入值! –

+0

其實我不得不對我的代碼進行一些修改,因爲仍然存在一些干擾handleClick的事情,並且它一直沒有被觸發。所以我從輸入中刪除了'onBlur = {this.handleBlur}',因此我不再需要handleBlur函數的取消,直接調用handleBlur進入handleClick –