javascript 当我选择一条记录时,如何在选择的元素上设置选择的选项?

dxpyg8gm  于 2023-03-28  发布在  Java
关注(0)|答案(2)|浏览(91)

我有一个带有文本输入和三个选择的表单,这个表单用于执行CRUD,当按下此选项时,我可以选择编辑,表单输入将填充所选记录的信息,我实现了文本类型输入的正确填充,但我还没有能够得到选择输入设置与所选记录的选项。我能做些什么来实现这一点。

这是我的代码:

import React, { useEffect, useState } from "react";

const initialFormTeam = {
  equipos_id: null,
  nombre: "",
  entrenador: null,
  estatus: null,
  competencia: null,
  grupo: null,
};

function RegisterFormTeam(props) {
  const {
    createTeam,
    dataTrainer,
    dataStatus,
    dataCompetition,
    dataToEdit,
    setDataToEdit,
    updateTeam,
  } = props;

  //States
  const [form, setForm] = useState(initialFormTeam);
  const [message, setMessage] = useState();
  const [response, setResponse] = useState(null);
  const [selectValues, setSelectValues] = useState({
    trainer: "",
    status: "",
    competition: "",
  });

  useEffect(() => {
    if (dataToEdit) {
      setForm(dataToEdit);
    } else {
      setForm(initialFormTeam);
    }
  }, [dataToEdit]);

  const handleChange = (e) => {
    setForm({
      ...form,
      [e.target.name]: e.target.value,
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (form.equipos_id === null) {
      createTeam(form);
      setMessage("Team added successfully");
      setResponse(true);
      setTimeout(() => {
        setResponse(false);
      }, 3000);
    } else if (form.equipos_id !== null) {
      updateTeam(form, {
        nombre: form.nombre,
        entrenador: form.entrenador,
        estatus: form.estatus,
        competencia: form.competencia,
      });
    }
    setSelectValues({
      trainer: "",
      status: "",
      competition: "",
    });
    handleReset();
  };

  const handleSelect = (e) => {
    const fieldName = e.target.name;
    const fieldValue = e.target.value;

    if (fieldName === "entrenador") {
      setForm({
        ...form,
        entrenador: fieldValue,
      });
      setSelectValues({
        ...selectValues,
        trainer: fieldValue,
      });
    } else if (fieldName === "estatus") {
      setForm({
        ...form,
        estatus: fieldValue,
      });
      setSelectValues({
        ...selectValues,
        status: fieldValue,
      });
    } else if (fieldName === "competition") {
      setForm({
        ...form,
        competencia: fieldValue,
      });
      setSelectValues({
        ...selectValues,
        competition: fieldValue,
      });
    }
  };

  const handleReset = (e) => {
    setForm(initialFormTeam);
    setDataToEdit(null);
  };

  return (
    <div>
      <h1>Register your teams</h1>
      <form onSubmit={handleSubmit}>
        <h3>{dataToEdit ? "Edit" : "Add"}</h3>
        <label htmlFor="nombre">Name of the team </label>
        <input
          type="text"
          id="nombre"
          name="nombre"
          onChange={handleChange}
          value={form.nombre}
          placeholder="Write the name of the team"
        />
        <br />
        <br />
        <label htmlFor="trainer">Trainer </label>
        <select
          id="trainer"
          name="entrenador"
          onChange={handleSelect}
          value={selectValues.trainer}
        >
          <option value="" hidden>
            Select the trainer
          </option>
          {dataTrainer.length > 0 ? (
            dataTrainer[0].users.map((el, index) => (
              <option key={index} value={el.user_id}>
                {`${el.nombres} ${el.apellidos}`}
              </option>
            ))
          ) : (
            <option value="" disabled>
              Loading...
            </option>
          )}
        </select>
        <br />
        <br />
        <label htmlFor="status">Status </label>
        <select
          id="statusTeam"
          name="estatus"
          onChange={handleSelect}
          value={selectValues.status}
        >
          <option value="" hidden>
            Select status team
          </option>
          {dataStatus.length > 0 ? (
            dataStatus.map((el, index) => (
              <option key={index} value={el.catalogo_id}>
                {el.clave}
              </option>
            ))
          ) : (
            <option value="" disabled>
              Loading...
            </option>
          )}
        </select>
        <br />
        <br />
        <label htmlFor="competition">Competition </label>
        <select
          id="competitionTeam"
          name="competition"
          onChange={handleSelect}
          value={selectValues.competition}
        >
          <option value="" hidden>
            Select competition
          </option>
          {dataCompetition.length > 0 ? (
            dataCompetition.map((el, index) => (
              <option key={index} value={el.competicion_id}>
                {el.nombre}
              </option>
            ))
          ) : (
            <option value="" disabled>
              Loading...
            </option>
          )}
        </select>
        <br />
        <br />
        <input type="submit" value={dataToEdit ? "Edit" : "Add team"} />
        <input type="reset" value="Clear" onClick={handleReset}></input>
      </form>
      {response && <p>{message}</p>}
    </div>
  );
}

export default RegisterFormTeam;
const TableRowTeam = ({ el, deleteTeam, setDataToEdit, }) => {

  return (
    <tr>
      <td>{el.nombre}</td>
      <td>{`${el.users.nombres} ${el.users.apellidos}`}</td>
      <td>{el.catalogos.clave}</td>
      <td>{el.competicion.nombre}</td>
      <td>
        <button onClick={() => setDataToEdit(el)}>Edit</button>
        <button onClick={() => deleteTeam(el.equipos_id, el.nombre)}>
          Delete
        </button>
      </td>
    </tr>
  );
};
export default TableRowTeam;
oyt4ldly

oyt4ldly1#

如果所选属性(selected="selected")是当前选中的选项,则需要将其添加到<option>元素中。例如,如果培训师的用户ID(el.user_id)与当前选中的培训师(form.entrentador)相同,则需要添加所选属性。

4c8rllxm

4c8rllxm2#

我应用于解决我的问题的解决方案如下:因为selected属性在React中没有使用,所以你必须在select标签的根处使用value属性。所以使用value属性我们检查selected元素是否是当前选中的选项,如果form.competition不同于null,我们在select中设置selected值,否则我们将标签留空。

<label htmlFor="trainer">Trainer </label>
        <select
          id="trainer"
          name="entrenador"
          onChange={handleSelect}
          {...(form.entrenador !== null
            ? { value: form.entrenador }
            : { value: selectValues.trainer })}
        >
          <option value="" hidden>
            Select the trainer
          </option>
          {dataTrainer.length > 0 ? (
            dataTrainer[0].users.map((el, index) => (
              <option key={index} value={el.user_id}>
                {`${el.nombres} ${el.apellidos}`}
              </option>
            ))
          ) : (
            <option value="" disabled>
              Loading...
            </option>
          )}
        </select>

相关问题