1

我正在使用 react-date-picker,我想将它创建为一个日期选择器组件,我可以在页面的每个部分使用它。onchange 方法是我遇到问题的地方,因为在状态更改时,它不知道它正在更改的列。我在 onchange 方法中遗漏了一些东西。当我选择一个日期时,错误是状态总是为空。这是我控制台中的结果。

21/12/2018

export class DatePickerNew extends React.PureComponent<IIDateTimeProps, any> 
{
    classes: string[];
    constructor(props: IIDateTimeProps) {
        super(props);
        this.state = {
            dirty: false,
            valid: false,
            validated: false,
            maxLength: this.props.maxLength || 250,
            minLength: this.props.minLength || 1,
            minNumber: this.props.minNumber || 0,
            maxNumber: this.props.maxNumber || 999999999999999,
            type: "date",
            validationMessage: "",
            selected:""

        } 
    }
    onChange = date => {
        const result = Validation.inputValidation(date, this.state);
        //date = DateTime.parse(date, DateTime.dateOutPutFormat);
        this.setState({
            validated: true,
            valid: result.state,
            dirty: true,
          selected: moment(date).format('DD/MM/YYYY').toString(),
          value:this.state.selected

        });
        console.log(this.state.value)
        console.log(this.state.selected)
      };

render() {
        this.classes = this.props.classes || [];

        return (
            <ErrorBoundary errorMessage="Error rendering DatePicker">

                  <DatePick

                    id={this.props.id}
                    name={this.props.name}
                    title={this.props.title}  
                    required={this.props.required}

                    value={this.state.selected}
                    onChange={this.onChange}

                    peekNextMonth
                    showMonthDropdown
                    showYearDropdown
                    dropdownMode="select"
                    type="text"
                    placeholderText="DD/MM/YYYY"
                    />


            </ErrorBoundary>);
    }
}

这就是我在另一个组件中调用它的方式

<DatePickerNew 
id="holidayDate" 
title="Holiday Date" 
label="Holiday Date"
type="text"
required={true} 
name="holidayDate"
isClearable={true}

/>
4

2 回答 2

1

当您想将参数传递给函数时,您必须绑定或调用回调函数!

onChange={this.onChange} //错误的方式

解决方案是:

onChange={() => this.onChange(date)} //The most used way!

或者

onChange={this.onChange.bind(this,date)}

其中之一应该为您工作!

于 2018-12-12T18:38:16.103 回答
0

您是否在构造函数中绑定了 onChange 方法?像这样:

constructor(props) {
  super(props);
  this.onChange = this.onChange.bind(this);
}

我去掉了一些其他的东西,只专注于事件绑定。这里还通过他们的文档对表单等进行了更大的细分:https ://reactjs.org/docs/forms.html

此外,这是超级挑剔的,但对于这种情况,handleChange 将比 onChange 更具语义。

于 2018-12-12T18:22:14.950 回答