reactjs 如何使用React在按钮中附加“disable”属性

mnemlml8  于 2022-12-22  发布在  React
关注(0)|答案(2)|浏览(364)

我正在处理Reactjs/nextjs,我想添加/删除“disable”属性,我该怎么做?下面是我当前的代码

const handleSubmit = (e) => {
    e.preventDefault();
    //Should append "disable" on submit button
    axios
    .post("xxxxxxxxxxxxxxxxxxxxxxxxxxx",data
    )
    .then(function (response) {
       //Should remove "disable" after response
    }
    });
}

<form className="row" id="home_contact_form" onSubmit={handleSubmit}>
<input type="submit" value="send" className="sendbtn" id="sendbtn" />
</form>
vnjpjtjt

vnjpjtjt1#

您应该创建一个useState,在请求过程中设置true或false
示例:

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [isDisabled, setIsDisabled] = useState(false);

  const handleSubmit = () => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => {
        setIsDisabled(true);
        return response.json();
      })
      .then((json) => console.log(json))
      .finally(() => setIsDisabled(false));
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button disabled={isDisabled} onClick={handleSubmit}>
        Submit
      </button>
    </div>
  );
}
vwkv1x7d

vwkv1x7d2#

您可以为此作业创建一个布尔状态,最初,在调用handleSubmit函数时,您的状态应为false,然后将状态设置为true,一旦从API获得响应,则再次将状态更新为false。
那么你可以简单地在你的输入中使用那个状态

<input type="submit" value="send" className="sendbtn" id="sendbtn" disabled={isDisabled} />

相关问题