1

如何识别用户是否通过按“Enter”按钮或单击鼠标来选择数据?

下面是我的代码:

<SingleDatePicker
    date={this.state.date}
    isOutsideRange={() => false}
    isDayHighlighted={day => isSameDay(moment(new Date()),moment(day))}
    daySize={30}
    verticalSpacing={2}
    onDateChange={date => {
        this.setState({ date });
        if(date) {
            this.props.onSaveValue(date.unix());
        }
    }}
    displayFormat={this.props.dateFormat}
    focused={this.state.focused}
    numberOfMonths={1}
    placeholder={this.props.dateFormat}
    onFocusChange={({ focused }) =>{
        this.setState({ focused });
        this.props.isCalendarOpen(focused)
    }}
/>

我很简单SingleDatePicker,我没有找到某种方法来识别用户如何选择数据,没有addeventlisener其他听众。

4

1 回答 1

0

根据ReactJS 的SyntheticEvent文档,

  1. 要确定是否Enter被击中,您可以onChange对输入使用方法调用。
  2. 要识别鼠标事件,可以使用onClick点击事件来识别。因此代码应如下所示;

    constructor(props) {
        super(props);
        this.handleEvent = this.handleCommonEvent.bind(this);
    }
    
    handleCommonEvent: function(e) {
        if(e.nativeEvent 
           && e.nativeEvent.type 
           && e.nativeEvent.type == 'click'){
             // do something here on mouse click
        } else if(e.nativeEvent 
           && e.nativeEvent.type 
           && e.nativeEvent.type == 'input'){
           // do something here on keyboard input
        }
    
    }
    

在您的输入字段中添加以下内容。

<...onClick={ this.handleEvent } onChange={ this.handleEvent }..../>

注意e是合成事件。React 根据W3C 规范定义了这些合成事件,因此您无需担心跨浏览器的兼容性。

于 2018-05-12T14:17:55.813 回答