0

我有这个表单组件,您可以在单击按钮时添加一些字段。这意味着我在现有组件中添加了一个组件。

想法是用户可以添加他们想要的任何字段集,然后提交并创建一个充满训练对象的一天的模板。需要控制输入,因为当表单使用新字段重新呈现时,以前键入的值必须保持不变。

但这里的问题是,当我键入每个字符时,输入会被渲染并且失去焦点。所以我需要再次选择并输入。帮助?

你可以在这里查看:它在前端的外观

这是完整组件的代码:

import React, { useState } from "react";
import { useMutation } from "@apollo/client";
import { useForm } from '../../utils/hooks'
import { Button, Form } from "semantic-ui-react";

import { FETCH_TEMPLATES_QUERY, ADD_TEMPLATES_MUTATION } from '../../utils/graphql'

//hook for form functioning
function AddTemplateForm(props) {

  const { values, onChange, onSubmit } = useForm(createDayCallback, {
    date: '',
    // dayTrainings:[]
  });
  //addTraningObject State 
  const [trainingObjects, setTrainingObjects] = useState([]);

  //apollo hook to send data through GraphQL    
  const [createDay, { error }] = useMutation(ADD_TEMPLATES_MUTATION, {
    errorPolicy: 'all',
    variables: { values, trainingObjects },
    update(proxy, result) {
      const data = proxy.readQuery({
        query: FETCH_TEMPLATES_QUERY,
      });

      proxy.writeQuery({
        query: FETCH_TEMPLATES_QUERY,
        data: {
          getDays: [result.data.createDay, ...data.getDays]
        }
      })

      props.history.push('/templates')
    },
  },
    {});

  function createDayCallback() {
    createDay();
  }





  //addTraningObject function
  function addTraining() {
    // console.table(trainingObjects);
    // let newCount = trainingObjects.length + 1;
    // console.log(newCount)
    const newTrainingObject = {
      time: "",
      training: "",
      // id: newCount
    };

    setTrainingObjects([...trainingObjects, newTrainingObject]);
  }



  function updateObjectValues(event, index) {

    const { name, value } = event.target;
    let values = [...trainingObjects]
    values[index][name] = value
    setTrainingObjects(values)
    console.table(trainingObjects)
    // fix state from updating not to lose values
    // send the values through form 

  }



  //little component I want to dynamically add each time people press a button  
  const AddDayTraining = ({ trainingObject, trainingItemIndex }) => {
    // console.log(trainingObject)

    let isThat = trainingObjects.find(item =>
      item.id === trainingObject.id)

    return (

      <>
        <Form.Field>
          <Form.Input
            placeholder="time"
            name="time"
            onChange={
              //  (event)=>
              //  console.log(event.target.value)
              (event) => updateObjectValues(event, trainingItemIndex)
            }
            value={trainingObjects[trainingItemIndex].time}
            error={error ? true : false}
          />
          <Form.Input
            placeholder="training"
            name="training"
            onChange={(event) => updateObjectValues(event, trainingItemIndex)}
            value={trainingObjects[trainingItemIndex].training}
            error={error ? true : false}
          />
        </Form.Field>
      </>
    )
  }

  //Form component itself
  const AddTemplateForm = (
    <>
      <Form onSubmit={onSubmit}>
        <h2>Add a template :</h2>
        <Form.Field>
          <Form.Input
            placeholder="date"
            name="date"
            onChange={onChange}
            values={values.date}
            error={error ? true : false}
          />
        </Form.Field>
        <Form.Field>
          <Button type="button" onClick={addTraining}>Add training</Button>
        </Form.Field>

        <div className='list of trainings'>
          {trainingObjects.length === 0 ? "" : trainingObjects.map((trainingObject, index) => (

            AddDayTraining(
              {
                trainingObject: trainingObject, trainingItemIndex: index,
                key: index
              }
            )


          ))}
        </div>


        <Button type="submit" color="teal">Submit</Button>

      </Form>

      {error && (
        <div className="ui error message" style={{ marginBottom: 20 }}>
          <li>{error.graphQLErrors[0].message}</li>
        </div>
      )}

    </>
  )
  return AddTemplateForm
}
export default AddTemplateForm;

4

0 回答 0