首页 > 解决方案 > 如果文本框为空,我想禁用按钮

问题描述

return (
    {jobstate.jobs.map((data,i) =>{ 
  <form>
    <input type="text" placeholder="Post a comment" onChange={(e) => jobcmthandler(e,data._id,i) } />
    <button type="button" onClick={postcmt} >Send</button>
  </form>
   })}
)

我使用 map 函数生成动态 HTML,如果文本为空,我想禁用按钮,以及如何在反应 js 中单击按钮时获取文本值

标签: javascriptreactjsreact-nativemern

解决方案


我真的不明白你为什么要这样做,但你去(例子):

import React, { useState } from "react";

export default function App() {
  return ["Name", "Age"].map((label) => <Form label={label} />);
}

function Form({ label }) {
  const [readValue, writeValue] = useState("");
  return (
    <form>
      <label>{label}</label>
      <input
        type="text"
        placeholder="Post a comment"
        onChange={(e) => writeValue(e.target.value)}
        value={readValue}
      />
      <button
        type="button"
        onClick={() => console.log("Submit")}
        disabled={readValue === ""}
      >
        Send
      </button>
    </form>
  );
}


推荐阅读