【问题标题】:react ternary operator problem, solvable only with jquery?反应三元运算符问题,只能用jquery解决?
【发布时间】:2021-12-06 04:08:34
【问题描述】:

我是 React 新手,并尝试使用 Springboot 制作一个简单的 crud。 在某些时候我需要使用三元运算符,但它不起作用。我之前在 React 中使用它没有问题,我不明白为什么现在不起作用。 所以我使用了一个函数并且正在工作,除非我必须清空一个 div,这给了我一个问题并且需要使用 jquery。所以现在代码正在运行,我只想知道我在三元和用javascript清空div时做错了什么。 我将发布完整的工作代码,然后只是想要使用的代码与实际工作的代码。 感谢您的耐心等待

import { React, useState, useEffect } from "react";
import { useHistory } from "react-router";
import ServiceUtente from "../service/ServiceUtente";
import $ from "jquery";

const Utente = () => {
  const history = useHistory();
  const [utenti, setUtenti] = useState([]);
  const [isDeleted, setIsDeleted] = useState(false); 
  const [searchBy, setSearchBy] = useState("");
  let checkedNome = false;
  let checkedEmail = false;
  let checkedProfilo = false;

  useEffect(() => {
    retrieveUtenti();
  }, [isDeleted]);

  // retrieve data from db and store it into utenti
  const retrieveUtenti = () => {
    ServiceUtente.utenteGetAll()
      .then((response) => {
        setUtenti(response.data);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const viewUtente = (id) => {
    history.push(`/view-utente/${id}`);
  };

  const aggiungiUtente = () => {
    history.push("/aggiungi-update-utente/_add");
  };

  const deleteUtente = (id) => {
    ServiceUtente.utenteDelete(id)
      .then((response) => {
        setIsDeleted(!isDeleted);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const updateUtente = (id) => {
    history.push(`/aggiungi-update-utente/${id}`);
  };

  const handleSearch = (e) => {
    setSearchBy(e.target.value);
  };

  const handleNome = (e) => {
    checkedNome = e.target.checked;
    console.log("nome: " + checkedNome);
    nomeForm();
  };
  const handleEmail = (e) => {
    checkedEmail = e.target.checked;
    console.log("email: " + checkedEmail);
  };
  const handleProfilo = (e) => {
    checkedProfilo = e.target.checked;
    console.log("profilo: " + checkedProfilo);
  };

  const formSearchBy = () => {
    // console.log("");
  };

  const nomeForm = () => {
    if (checkedNome === true) {
      document.getElementById("nomeForm").innerHTML = `
        <input
          type="text"
          className="form-control"
          placeholder="Search Utente"
          value="${searchBy}"
          onChange="${handleSearch}"
        />`;
    } else {
      // document.getElementById("nomeForm").innerHTML = "";
      $("#nomeForm").empty();
    }
  };

  return (
    <div className="row">
      <div className="col-sm-10 offset-1">
        <h2 className="login-title my-4" style={{ textAlign: "center" }}>
          GM Utente
        </h2>

        {/* ***********************SEARCH BAR****************************************** */}
        <form onClick={formSearchBy}>
          <h4 style={{ textAlign: "center" }}>
            Spuntare i campi desiderati per la ricerca
          </h4>
          <div className="form-check">
            <input
              onChange={handleNome}
              className="form-check-input"
              type="checkbox"
              name="nomeCheck"
              value=""
              id="nomeUtente"
            />
            <label className="form-check-label" htmlFor="nomeUtente">
              Nome Utente
            </label>
            <div id="nomeForm">{nomeForm()}</div>
          </div>
          <div
            className="input-group-append my-2 text-center"
            style={{ textAlign: "center" }}
          >
            <button
              className="btn btn-success"
              type="submit"
              id="button-addon2"
            >
              Search
            </button>
          </div>
        </form>
        {/* ***********************END SEARCH BAR*********************************** */}

        <button
          type="button"
          className="btn btn-primary my-2"
          onClick={() => aggiungiUtente()}
        >
          Aggiungi Utente
        </button>
        <table
          className="table table-striped table-bordered"
          style={{ textAlign: "center" }}
        >
          <thead>
            <tr>
              <th>Id Utente</th>
              <th>Nome Utente</th>
              <th>Email</th>
              <th>Password</th>
              <th>Profilo Utente</th>
              <th>Azioni</th>
            </tr>
          </thead>

          <tbody>
            {utenti.map((utente) => (
              <tr key={utente.idUtente}>
                <td>{utente.idUtente}</td>
                <td>{utente.nomeUtente}</td>
                <td>{utente.email}</td>
                <td>{utente.password}</td>
                <td>{utente.profiloUtente.nomeProfilo}</td>
                <td>
                  <button
                    onClick={() => viewUtente(utente.idUtente)}
                    type="button"
                    className="btn btn-secondary mx-1"
                  >
                    Details
                  </button>
                  <button
                    onClick={() => updateUtente(utente.idUtente)}
                    type="button"
                    className="btn btn-warning mx-1"
                  >
                    Update
                  </button>
                  <button
                    onClick={() => deleteUtente(utente.idUtente)}
                    type="button"
                    className="btn btn-danger mx-1"
                  >
                    Delete
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};

export default Utente;

所有这些代码都在工作,但我想使用它

{checkedNome === true ? (
              <input
                type="text"
                className="form-control"
                placeholder="Search Utente"
                value={searchBy}
                onChange={handleSearch}
              />
            ) : null}

代替这个函数

const nomeForm = () => {
    if (checkedNome === true) {
      document.getElementById("nomeForm").innerHTML = `
        <input
          type="text"
          className="form-control"
          placeholder="Search Utente"
          value="${searchBy}"
          onChange="${handleSearch}"
        />`;
    } else {
      // document.getElementById("nomeForm").innerHTML = "";
      $("#nomeForm").empty();
    }
  };

此外,在此函数中,为什么 Jquery 语法有效以及 '.innerHTML = "";'注释掉是不是? 谢谢

【问题讨论】:

  • 你不需要使用jQuery来实现你想要的。带有三元运算符的代码看起来很好,应该放在div id 为“nomeForm”。尝试这样做时遇到什么问题?
  • "在某些时候我需要使用三元运算符,但它不起作用"请详细说明但它不起作用 部分。
  • 而不是使用明确返回 null 的三元运算符,使用条件和运算符示例:{checkedNome &amp;&amp; &lt;input /&gt;} 让我知道这是否有效
  • 如果我不使用 jQuery,我会得到“TypeError: Cannot set properties of null (setting 'innerHTML')”,document.getElementById("nomeForm").innerHTML = "";
  • 感谢 Houssam 和 Varun,现在我会尝试。 Felix Kling,它不起作用意味着我单击复选框并且没有任何反应

标签: javascript jquery reactjs conditional-operator


【解决方案1】:

问题

问题是您没有更新任何状态来触发渲染。 checkedNome 在函数体中声明,改变它不会触发 React 做任何事情。

let checkedNome = false;

const handleNome = (e) => {
  checkedNome = e.target.checked; // <-- mutation
  console.log("nome: " + checkedNome);
  nomeForm(); // <-- DOM mutation
};

解决方案

checkedNome 移动到组件状态:

const [checkedNome, setCheckedNome] = React.useState(false);

更新 handleNome 以将状态更新加入队列:

const handleNome = (e) => {
  const { checked } = e.target;
  setCheckedNome(checked);
};

更新渲染返回以有条件地渲染输入:

<div id="nomeForm">
  {checkedNome && (
    <input
      type="text"
      className="form-control"
      placeholder="Search Utente"
      value={searchBy}
      onChange={handleSearch}
    />
  )}
</div>

【讨论】:

  • 非常感谢,这正在工作!还有一个问题,为什么在更新handleNome 时我需要将const { checked } 放在大括号中?再次感谢!
  • @fax58 是解构赋值,const { checked } = e.target;const checked = e.target.checked; 的简写。您不需要这样做,但我认为它往往会导致代码更简洁。
猜你喜欢
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 2018-04-11
  • 1970-01-01
  • 2018-01-26
  • 2019-07-19
  • 2016-08-09
相关资源
最近更新 更多