如何使用 Material UI 在 TextField 变红之前等待用户输入

发布于 2025-01-13 20:51:14 字数 2179 浏览 3 评论 0原文

我正在使用 React 和 Material UI 制作一个简单的注册页面。 但用户总是会得到带有我的代码的红色文本字段。

如何让它等待用户第一次尝试输入然后给出反馈(红色或不红色)?

注册页面的图片

这是我当前的代码

         <Box
            component="form"
            sx={{ '& > :not(style)': { m: 1, width: '25ch' } }}
            noValidate
            autoComplete="off"
          >
            <TextField
              id="outlined-basic"
              label="First Name"
              onChange={(event) => setFirstName(event.target.value)}
              variant="outlined"
              error={!firstName}
              required
            />
            <TextField
              id="outlined-basic"
              label="Last Name"
              onChange={(event) => setLastName(event.target.value)}
              variant="outlined"
              error={!lastName}
              required
            />
            <TextField
              id="outlined-basic"
              label="Home Number"
              onChange={(event) => setHomeNumber(event.target.value)}
              variant="outlined"
              type="tel"
              error={!homeNumber}
              required
            />
            <TextField
              id="outlined-basic"
              label="Address"
              onChange={(event) => setAddress(event.target.value)}
              variant="outlined"
              error={!address}
              required
            />
            <TextField
              id="outlined-basic"
              label="Email"
              onChange={(event) => setEmail(event.target.value)}
              variant="outlined"
              type="email"
              error={!email}
              required
            />
            <TextField
              id="outlined-password-input"
              label="Password"
              onChange={(event) => setPassword(event.target.value)}
              type="password"
              autoComplete="off"
              error={!password}
              required
            />
         </Box>

I am making a simple sign up page on react and using Material UI.
But the user would always get the red TextField with my code.

How to make it wait for the user to first try to input then it would give a feedback (either red or not)?

a picture of the sign up page

This is my current code

         <Box
            component="form"
            sx={{ '& > :not(style)': { m: 1, width: '25ch' } }}
            noValidate
            autoComplete="off"
          >
            <TextField
              id="outlined-basic"
              label="First Name"
              onChange={(event) => setFirstName(event.target.value)}
              variant="outlined"
              error={!firstName}
              required
            />
            <TextField
              id="outlined-basic"
              label="Last Name"
              onChange={(event) => setLastName(event.target.value)}
              variant="outlined"
              error={!lastName}
              required
            />
            <TextField
              id="outlined-basic"
              label="Home Number"
              onChange={(event) => setHomeNumber(event.target.value)}
              variant="outlined"
              type="tel"
              error={!homeNumber}
              required
            />
            <TextField
              id="outlined-basic"
              label="Address"
              onChange={(event) => setAddress(event.target.value)}
              variant="outlined"
              error={!address}
              required
            />
            <TextField
              id="outlined-basic"
              label="Email"
              onChange={(event) => setEmail(event.target.value)}
              variant="outlined"
              type="email"
              error={!email}
              required
            />
            <TextField
              id="outlined-password-input"
              label="Password"
              onChange={(event) => setPassword(event.target.value)}
              type="password"
              autoComplete="off"
              error={!password}
              required
            />
         </Box>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

始终不够爱げ你 2025-01-20 20:51:14

实现这个需求的方法有很多种,我使用其中一种并制作demo给大家。

代码片段

  1. 添加验证状态(共有三种状态)是我的解决方案的核心。
  /**
   *  -1 : 'initial'
   *   0 : 'invalid'
   *   1 : 'valid'
   */
  const [validation, setValidation] = useState({
    firstName: -1,
    lastName: -1
  });
  1. 创建一个函数,每当输入发生变化时验证 key 的值是否有效,并给出相应的验证状态。
  // Verify that the value for the key.
  const verify = (k, v) => {
    setValidation((prev) => ({ ...prev, [k]: v ? 1 : 0 }));
  };

  const handleInputOnChange = (e) => {
    const k = e.target.name;
    const v = e.target.value;
    // Verify that the value for the key.
    verify(k, v);
    setData((prev) => ({ ...prev, [k]: v }));
  };
  1. 当提交事件或其他事件触发时,检查所有验证状态,将 -1 设置为 0,然后执行您想要的行为。
  const handleOnSubmit = () => {
    // when event trigger, check all validation if invalid set value to 0, and make red prompt.
    verifyAll();

    // check invalid
    if (Object.values(validation).some((v) => v !== 1)) {
      // if there is invalid value, do something.
      console.error("Invalid value.");
    } else {
      // if pass send data.
      console.info(data);
    }
  };
  1. HTML 样式基于验证状态,如果为 0,则出错并变为红色。
        <TextField
          id="outlined-basic"
          name="firstName"
          label="First Name"
          onChange={handleInputOnChange}
          variant="outlined"
          // only validation === 0, changed to red(error).
          error={validation["firstName"] === 0}
          required
        />

完整代码示例:

编辑文本字段选择开始

There are many ways to accomplish this requirement, I use one and make demo to you.

Code fragment

  1. Adding a verification state (there are three states) is the core of my solution.
  /**
   *  -1 : 'initial'
   *   0 : 'invalid'
   *   1 : 'valid'
   */
  const [validation, setValidation] = useState({
    firstName: -1,
    lastName: -1
  });
  1. Make a function that verifies whether the value of key are valid whenever the input on change, and gives the corresponding validation state.
  // Verify that the value for the key.
  const verify = (k, v) => {
    setValidation((prev) => ({ ...prev, [k]: v ? 1 : 0 }));
  };

  const handleInputOnChange = (e) => {
    const k = e.target.name;
    const v = e.target.value;
    // Verify that the value for the key.
    verify(k, v);
    setData((prev) => ({ ...prev, [k]: v }));
  };
  1. When a submit event or other event fires, check all validation states, set -1 to 0, and do the behavior you want.
  const handleOnSubmit = () => {
    // when event trigger, check all validation if invalid set value to 0, and make red prompt.
    verifyAll();

    // check invalid
    if (Object.values(validation).some((v) => v !== 1)) {
      // if there is invalid value, do something.
      console.error("Invalid value.");
    } else {
      // if pass send data.
      console.info(data);
    }
  };
  1. HTML style based on validation states, if 0, error and turn red.
        <TextField
          id="outlined-basic"
          name="firstName"
          label="First Name"
          onChange={handleInputOnChange}
          variant="outlined"
          // only validation === 0, changed to red(error).
          error={validation["firstName"] === 0}
          required
        />

Full code sample:

Edit TextField selectionStart

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文