简体   繁体   中英

id undefined in onChange event

Using react datepicker , I am trying to get the id of the clicked component

<DatePicker
id={cellData.column}
selected={DatePickerDate}
onChange={this.onDateRangePickerChange}
className='form-control'
                    />

In my click handler the event being passed is a moment date object, so event.currentTarget is undefined.

onDateRangePickerChange: function(event, picker){

        var localRowDataStack = _.cloneDeep(this.state.rowDataStack);
        localRowDataStack[event.currentTarget.id] = picker.startDate.format(appConfig.getKey('dateFormat'));
        this.setState({
            rowDataStack: localRowDataStack,
            isOmitReRender: false
        });

},

How can I get the id of the clicked datepicker?

You can as well extend onDateRangePickerChange to accept id and just pas it there like this:

<DatePicker
    id={cellData.column}
    selected={DatePickerDate}
    onChange={(e, p) => this.onDateRangePickerChange(e, p, cellData.column)}
    className='form-control'/>

You can set id as first argument to onDateRangePickerChange with .bind , and thus avoid add id as DatePicker attribute

onDateRangePickerChange: function (column, date) {
  console.log(column, date);
},

<DatePicker
  selected={ DatePickerDate }
  onChange={ this.onDateRangePickerChange.bind(this, cellData.column) }
  className="form-control"
/>;

You could try doing this way:

onDateRangePickerChange: function(event){

        var id = event.target.id;  // ID from the element
        var localRowDataStack = _.cloneDeep(this.state.rowDataStack);
        localRowDataStack[id] = picker.startDate.format(appConfig.getKey('dateFormat'));
        this.setState({
            rowDataStack: localRowDataStack,
            isOmitReRender: false
        });
},

You could see more examples/responses here: React.js: Identifying different inputs with one onChange handler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM