条件表单输入无响应

Conditional form input non-responsive

作为登录的一部分,我有一个无响应的条件输入;我可以专注于它,但单击后我只能非常快地写入它,但值已清除。我也尝试在它周围添加但没有运气。所有非条件输入功能正常。

https://codesandbox.io/s/frosty-wu-y5do4c

从“react”导入 React,{useState};

const EventSignUp = (props) => {
  let [email, setEmail] = useState("");
  let [name, setName] = useState("");
  let [zip, setZip] = useState("");

  let [agreeTerms, setAgreeTerms] = useState(false);
  let [rememberMe, setRememberMe] = useState(false);
  let [country, setCountry] = useState("");

  const InputCountry = () => {
    return (
      <div>
        <input
          placeholder="Country"
          type="country"
          name="country"
          onChange={(e) => setCountry(e.target.value)}
        />
      </div>
    );
  };

  return (
    <form id="form_login_email" method="post">
      <input
        placeholder="Name*"
        type="name"
        name="name"
        onChange={(e) => setName(e.target.value)}
      />
      <input
        placeholder="E-mail*"
        type="email"
        name="email"
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        placeholder="E-mail again*"
        type="email"
        name="email"
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        placeholder="Zip/Postal Code"
        type="zip"
        name="zip"
        onChange={(e) => setZip(e.target.value)}
      />
      <InputCountry />
    </form>
  );
};

export default EventSignUp;

将 InputCountry 移到 EventSignup 组件之外,因为每次在国家/地区输入中输入值时,都会导致 re-rendering 并重新创建组件。此外,在国家/地区输入上添加了一个 value 属性以使其受控输入。


import React, { useState } from "react";

const InputCountry = ({ country, setCountry }) => {
  return (
    <div>
      <input
        placeholder="Country"
        type="country"
        name="country"
        value={country}
        onChange={(e) => setCountry(e.target.value)}
      />
    </div>
  );
};

const EventSignUp = (props) => {
  let [email, setEmail] = useState("");
  let [name, setName] = useState("");
  let [zip, setZip] = useState("");

  let [agreeTerms, setAgreeTerms] = useState(false);
  let [rememberMe, setRememberMe] = useState(false);
  let [country, setCountry] = useState("");

  return (
    <form id="form_login_email" method="post">
      <input
        placeholder="Name*"
        type="name"
        name="name"
        onChange={(e) => setName(e.target.value)}
      />
      <input
        placeholder="E-mail*"
        type="email"
        name="email"
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        placeholder="E-mail again*"
        type="email"
        name="email"
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        placeholder="Zip/Postal Code"
        type="zip"
        name="zip"
        onChange={(e) => setZip(e.target.value)}
      />
      <InputCountry country={country} setCountry={setCountry} />
    </form>
  );
};

export default EventSignUp;