【问题标题】:Disable and enable button after checking some condition检查某些条件后禁用和启用按钮
【发布时间】:2021-02-11 08:14:51
【问题描述】:

我这里有这个按钮

<button className={Classes.Button}
    disabled={!isEnabled}
    type="submit">
        {buttonText}
</button>

在检查我的一些输入值后应该禁用或启用它。 条件

const canBeSubmitted = () => {
    return (
      customerData.firstNameState.length > 0 && // TextInput
      customerData.emailState.length > 0 && // TextInput
      customerData.companeyState.length > 0 && // TextInput
      customerData.selected.length > 0 &&   // Dropdown
      customerData.agree === true // checkbox for terms
    );
  };
  let isEnabled = canBeSubmitted();

顺便说一句:同意复选框由其处理程序选中并且工作正常。 状态和处理程序中的agreement值为false

 const handleChange = (event) => {
    const field = event.target.id;
    if (field === "firstName") {
      setFirstName({ firstName: event.target.value });
    } else if (field === "email") {
      setEmail({ email: event.target.value });
    } else if (field === "country") {
      setSelected({ country: event.target.value });
    } else if (field === "agree") {
      setAgree(!agree);
      console.log(agree);
    }
  };

但总是返回 false。我错过了什么?

请帮帮我

【问题讨论】:

  • 你在复选框中传递了什么值? === 是一个严格的相等比较运算符,如果您将 true 作为字符串传递,那么它可能会导致问题。
  • 你检查了很多东西,也许你应该把它们全部注释掉,然后只注释一个,看看哪个语句导致了问题。还有为什么你有 !isEnabled 而不仅仅是 isEnabled?
  • @devin 我按照你的建议做了谢谢,问题来自前三个条件。但是如何检查用户是否输入了输入?
  • 如果costumerData.selected 是一个复选框,则不应检查其长度是否有效。
  • @steven7mwesigwa 谢谢,没有costumerData.selected 是一个下拉菜单,agree 是一个用于条款的复选框,另外3 个是文本输入。

标签: javascript html reactjs jsx


【解决方案1】:

如果我是正确的,你的“状态”不会因为你在handleChange胖箭头函数中改变“状态变量”而改变。

根据你的“状态”的结构,我可能是错的。

我假设你的“状态”结构是这样的。

const [firstName, setFirstName] = useState("");
const [email, setEmail] = useState("");
const [country, setCountry] = useState("");
const [agree, setAgree] = useState(false);    
  1. 修复您的 handleChange 函数。
// Commented out your possibly erroneous code.
const handleChange = (event) => {
    const field = event.target.id;

    if (field === "firstName") {
        // Fix here.
        // setFirstName({ firstName: event.target.value }); ❌
        setFirstName(event.target.value); ✅
    } else if (field === "email") {
        // Fix here.
        // setEmail({ email: event.target.value }); ❌
        setEmail(event.target.value); ✅
    } else if (field === "country") {
        // Fix here.
        // setSelected({ country: event.target.value }); ❌
        setCountry(event.target.value); ✅
    } else if (field === "agree") {
        // Fix here.
        // setAgree(!agree); ❌
        setAgree(event.target.checked); ✅
        console.log(agree);
    }
};
  1. 然后您可以像这样执行验证:
const canBeSubmitted = () => {
    return (
    firstName.trim().length && // TextInput
    email.trim().length && // TextInput
    country.trim().length && // Dropdown
    agree // checkbox for terms
    );
};
  1. 您的“countryState”似乎也有错字:
customerData.companeyState.length > 0 && // TextInput
  1. 您的代码中的&amp;&amp; 运算符之后似乎有一个句号。
customerData.selected.length > 0 &&.   // Dropdown

附录

@Harry9345,你也可以彻底摆脱handleChange

完整的源代码如下演示: https://codesandbox.io/s/crimson-fog-vp19s?file=/src/App.js

import { useEffect, useState } from "react";

export default function App() {
  const [firstName, setFirstName] = useState("");
  const [email, setEmail] = useState("");
  const [country, setCountry] = useState("");
  const [agree, setAgree] = useState(false);

  const canBeSubmitted = () => {
    const isValid =
      firstName.trim().length && // TextInput
      email.trim().length && // TextInput
      country.trim().length && // Dropdown
      agree; // checkbox for terms

    if (isValid) {
      document.getElementById("submitButton").removeAttribute("disabled");
    } else {
      document.getElementById("submitButton").setAttribute("disabled", true);
    }
    console.log({ firstName, email, country, agree });
  };

  useEffect(() => canBeSubmitted());

  return (
    <div>
      <form action="" method="post" id="form">
        <label htmlFor="firstName">First name:</label>
        <br />
        <input
          type="text"
          id="firstName"
          name="firstName"
          value={firstName}
          onChange={(e) => setFirstName(e.target.value)}
        />
        <br />
        <label htmlFor="email">Email Address:</label>
        <br />
        <input
          type="email"
          id="email"
          name="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
        />
        <br />
        <label htmlFor="country">Choose a country:</label>
        <br />
        <select
          id="country"
          name="country"
          value={country}
          onChange={(e) => setCountry(e.target.value)}
        >
          <option value="">Select..</option>
          <option value="1">USA</option>
          <option value="2">Canada</option>
          <option value="3">Algeria</option>
        </select>
        <br />
        <input
          type="checkbox"
          name="agree"
          id="agree"
          onClick={(e) => setAgree(e.target.checked)}
        />
        <label> I agree.</label>
        <br />
        <button type="submit" id="submitButton">
          Submit
        </button>
      </form>
    </div>
  );
}

【讨论】:

  • 非常感谢你的帮助,DOT " . " 是在这里输入代码时的错字,我切换到 react-hooks-form 因为它更容易。
【解决方案2】:

你应该使用状态而不是变量:

我添加了一些例子:

import { useState } from "react";

const App = () => {
  const [isDisabled, setIsDisabled] = useState(true);
  const [checked, setChecked] = useState(false);

  const canBeSubmitted = () => {
    return checked ? setIsDisabled(true) : setIsDisabled(false);
  };

  const onCheckboxClick = () => {
    setChecked(!checked);
    return canBeSubmitted();
  };

  return (
    <div className="App">
      <input type="checkbox" onClick={onCheckboxClick} />
      <button type="submit" disabled={isDisabled}>
        Submit
      </button>
    </div>
  );
};

export default App;

codesandbox

当然这只是一个代码示例,效率不高。

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 2017-08-15
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    相关资源
    最近更新 更多