以react钩子形式设置DatePicker的值(来自antd)



我正试图弄清楚如何使用带有react钩子形式的antd中的DatePicker。

目前,我的尝试是:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import useForm from "react-hook-form";
import { withRouter } from "react-router-dom";
import { useStateMachine } from "little-state-machine";
import updateAction from "./updateAction";
import { Input as InputField, Form, Button, DatePicker, Divider, Layout, Typography, Skeleton, Switch, Card, Icon, Avatar } from 'antd';
import Select from "react-select";

const { Content } = Layout 
const { Text, Paragraph } = Typography;
const { Meta } = Card;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const Team = props => {
const { register, handleSubmit, setValue, errors } = useForm();
const [ dueDate, setDate ] = useState(new Date());
const [indexes, setIndexes] = React.useState([]);
const [counter, setCounter] = React.useState(0);
const { action } = useStateMachine(updateAction);
const onSubit = data => {
action(data);
props.history.push("./ProposalBudget");
};

// const handleChange = dueDate => setDate(date);
const handleChange = (e) => {
setValue("dueDate", e.target.value);
}

const onSubmit = data => {
console.log(data);
};
const addMilestone = () => {
setIndexes(prevIndexes => [...prevIndexes, counter]);
setCounter(prevCounter => prevCounter + 1);
};
const removeMilestone = index => () => {
setIndexes(prevIndexes => [...prevIndexes.filter(item => item !== index)]);
};
const clearMilestones = () => {
setIndexes([]);
};
useEffect(() => {
register({ name: dueDate }); // custom register antd input
}, [register]);

注意:我也尝试过名称:{${fieldName}.dueDate-也不起作用。

return (
<div>
<HeaderBranding />
<Content
style={{
background: '#fff',
padding: 24,
margin: "auto",
minHeight: 280,
width: '70%'
}}
>
<form onSubmit={handleSubmit(onSubit)}>

{indexes.map(index => {
const fieldName = `milestones[${index}]`;
return (
<fieldset name={fieldName} key={fieldName}>
<label>
Title:
<input
type="text"
name={`${fieldName}.title`}
ref={register}
/>
</label>
<label>
Description:
<textarea
rows={12}
name={`${fieldName}.description`}
ref={register}
/>
</label>
<label>When do you expect to complete this milestone? <br />


<DatePicker 
selected={ dueDate } 
// ref={register}
InputField name={`${fieldName}.dueDate`} 
onChange={handleChange(index)}
//onChange={ handleChange }
>
<input 
type="date" 
name={`${fieldName}.dueDate`} 
inputRef={register}
/>
</DatePicker>

</label>

<Button type="danger" style={{ marginBottom: '20px', float: 'right'}} onClick={removeMilestone(index)}>
Remove this Milestone
</Button>
</fieldset>
);
})}
<Button type="primary" style={{ marginBottom: '20px'}} onClick={addMilestone}>
Add a Milestone
</Button>
<br />
<Button type="button" style={{ marginBottom: '20px'}} onClick={clearMilestones}>
Clear Milestones
</Button>
<input type="submit" value="next - budget" />
</form>
</Content>

</div>  
);
};
export default withRouter(Team);

这会生成一个错误:TypeError:无法读取未定义的属性"value">

setValue是在handleChange中定义的。

我不清楚要让这个日期选择器正常工作,需要采取哪些步骤。我需要单独的选择功能吗?

有人想好如何插入这个日期选择器了吗?

我也试过:

const handleChange = (e) => {
setValue("dueDate", e.target.Date);
}

我试过:

const handleChange = (e) => {
setValue("dueDate", e.target.date);
}

但是每一代都有相同的错误

我已经构建了一个包装器组件,以便更容易地使用外部控制的组件:https://github.com/react-hook-form/react-hook-form-input

import React from 'react';
import useForm from 'react-hook-form';
import { RHFInput } from 'react-hook-form-input';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
function App() {
const { handleSubmit, register, setValue, reset } = useForm();
return (
<form onSubmit={handleSubmit(data => console.log(data))}>
<RHFInput
as={<Select options={options} />}
rules={{ required: true }}
name="reactSelect"
register={register}
setValue={setValue}
/>
<button
type="button"
onClick={() => {
reset({
reactSelect: '',
});
}}
>
Reset Form
</button>
<button>submit</button>
</form>
);
}

试试这个,让我知道它是否能让你在AntD的生活更轻松。

/* eslint-disable react/prop-types */
import React, { useState } from 'react';
import { DatePicker } from 'antd';
import { Controller } from 'react-hook-form';
import color from '../../assets/theme/color';
import DatePickerContainer from './DatePickerContainer';
function DatePickerAntd(props) {
const { control, rules, required, title, ...childProps } = props;
const { name } = childProps;
const [focus, setFocus] = useState(false);
const style = {
backgroundColor: color.white,
borderColor: color.primary,
borderRadius: 5,
marginBottom: '1vh',
marginTop: '1vh',
};
let styleError;
if (!focus && props.error) {
styleError = { borderColor: color.red };
}
return (
<div>
<Controller
as={
<DatePicker
style={{ ...style, ...styleError }}
size="large"
format="DD-MM-YYYY"
placeholder={props.placeholder || ''}
onBlur={() => {
setFocus(false);
}}
onFocus={() => {
setFocus(true);
}}
name={name}
/>
}
name={name}
control={control}
rules={rules}
onChange={([selected]) =>  ({ value: selected })}
/>
</div>
);
}
export default DatePickerAntd;

我的容器父级使用的react钩子

const { handleSubmit, control, errors, reset, getValues } = useForm({
mode: 'onChange',
validationSchema: schema,
});
<DatePickerAntd
name="deadline"
title={messages.deadline}
error={errors.deadline}
control={control}
required={isFieldRequired(schema, 'deadline')}
/>

这样,它对我有效;-(

试试这个:

<DatePicker 
selected={ dueDate } 
// ref={register}
InputField name={`${fieldName}.dueDate`} 
onChange={()=>handleChange(index)}
//onChange={ handleChange }
>
<input 
type="date" 
name={`${fieldName}.dueDate`} 
inputRef={register}
/>

看起来,如果您使用onChange={handleChange(index)},它不会传递函数,而是传递该函数的执行结果。

如果您试图访问handleChange中的event,则应该从绑定范围手动传递if,否则它将是undefined

onChange={()=>handleChange(index, event)}

相关内容

  • 没有找到相关文章

最新更新