gpt4 book ai didi

javascript - React onChange 方法不改变对象的状态

转载 作者:行者123 更新时间:2023-11-30 19:57:45 26 4
gpt4 key购买 nike

我正在使用 react-date-picker,我想将它创建为一个日期选择器组件,我可以在我的页面的每个部分使用它。 onchange 方法是我遇到问题的地方,因为在状态更改时,它不知道它正在更改的列。我在 onchange 方法中遗漏了一些东西。当我选择一个日期时,得到的错误是 The state is always empty.This is the results in my console.

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}

/>

最佳答案

当你想将参数传递给你必须绑定(bind)或调用回调函数的函数时!

onChange={this.onChange}//方法不对

解决方法是:

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

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

其中一个应该适合您!

关于javascript - React onChange 方法不改变对象的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53749017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com