[英]React Antd not able to get value from custom date picker
I am currently using custom datepicker to enter date in the format 'MMDD' or 'MMDDYY' and setting the value in state and using in the datepicker component as controlled component.我目前正在使用自定义日期选择器以“MMDD”或“MMDDYY”格式输入日期,并将值设置为状态并在日期选择器组件中用作受控组件。 But on submit of form the datepicker value is undefined.
但是在提交表单时,日期选择器的值是未定义的。
Please find the code in the codesandbox and correct me on what i am doing wrong in this one.请在代码框中找到代码,并纠正我在此代码中做错了什么。
https:\/\/codesandbox.io\/s\/damp-haze-mmj80<\/a>
https:\/\/codesandbox.io\/s\/damp-haze-mmj80<\/a>
I've not used that library (antd), but looking at the docs for it, using that fieldDecorator adds two properties to the component -- onChange and value.我没有使用过那个库 (antd),但是查看了它的文档,使用那个 fieldDecorator 向组件添加了两个属性——onChange 和 value。
{getFieldDecorator("date-picker")(<CustomDatePicker />)}
So now imagine CustomDatePicker has those two properties.所以现在想象 CustomDatePicker 有这两个属性。 Value will be the value of the form item, and onChange is expecting to be called as the onChange handler of a form input.
Value 将是表单项的值,并且 onChange 期望作为表单输入的 onChange 处理程序被调用。
However, in your CustomDatePicker component you aren't doing anything with either of those.但是,在您的 CustomDatePicker 组件中,您没有对其中任何一个进行任何操作。 Instead, you're tracking the value (and updating it with a handler) locally to that component with local state.
相反,您正在本地跟踪具有本地状态的组件的值(并使用处理程序更新它)。
Instead, you should use those two properties:相反,您应该使用这两个属性:
class CustomDatePicker extends React.Component {
state = {
isOpen: false
};
render() {
return (
<DatePicker
value={this.props.value}
format={this.state.isOpen ? ["MMDD", "MMDDYY"] : "MM/DD/YY"}
placeholder=" -- Select Date --"
disabledDate={d => d && d > moment(Date.now())}
onOpenChange={status => {
this.setState({ isOpen: status });
}}
onChange={this.props.onChange}
/>
);
}
}
If you want to do any initial value logic, or validation, you'll do that at the form-level component -- the one that is controlling the state.如果您想执行任何初始值逻辑或验证,您将在表单级组件中执行此操作——控制状态的组件。
This is what works for me with React Hooks, hope it will help.这就是 React Hooks 对我有用的方法,希望它会有所帮助。
const initialInfo = {email: "", registrationDate: ""}
const [infoData, setInfoData] = useState(initialInfo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.