web-dev-qa-db-ja.com

react-hooks-formで(antdからの)DatePickerの値を設定する

私は、antdからの日付ピッカーをreact-hooks-formで使用する方法を理解しようとしています。

現在、私の試みは:

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:未定義のプロパティ '値'を読み取れません

setValueは、handleChangeで定義されています。

この日付ピッカーを機能させるためにどのステップが優れているかははっきりしていません。別の選択機能が必要ですか?

このデートピッカーを接続する方法を誰かが理解しましたか?

私も試しました:

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

そして私は試しました:

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

これらの各世代は同じエラー

3
Mel
/* 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-hooks-formを使用します

  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')}
            />

そのように、それは私のために働きます;-)

1
Massimo Alvaro