无法绑定React钩子上的单选按钮和复选框数据

时间:2020-10-15 06:39:10

标签: react-hooks

我有一个表单,当我提交数据时,它将发送到服务器,并将数据显示在表格中。 在表中,我有一个编辑按钮,当单击“编辑”按钮时,数据应绑定到表单。 在这里,我无法绑定“输入”字段,但无法绑定单选和复选框...

const Form = () => {
    const [data, setdata] = useState({
        "UserName" : "",
          "dropDown" :"",
          "gender" : "",
          "checking" :""
    })

    const [update, setUpdate] = useState([])

    const handleChange =(e)=>{
     
        if(e.target.name !=="gender" && e.target.name !=="checking"){
            setdata({...data,[e.target.name]:e.target.value});
        }else if(e.target.name ==="gender"){
                let allgenders = document.getElementsByName("gender");
                allgenders.forEach((allradio)=>{
                          if(allradio.checked){
                            setdata({...data,[e.target.name]:e.target.value});    
                          }
                })
        }else if(e.target.name ==="checking"){
                  let getallCheckboxes =[];
                  let allCheckboxes =document.getElementsByName("checking");
                  allCheckboxes.forEach((allchecks)=>{
                                if(allchecks.checked){
                                    getallCheckboxes.push(allchecks.value)
                                }
                  });
                  setdata({...data,[e.target.name]:getallCheckboxes});     
                  
        }

    }
    useEffect(() => {
        getAllData();
}, [])

   const handleSubmit=(e)=>{
    e.preventDefault();
    // setUpdate({...data,update});
    // console.log(data);
      axios.post('http://localhost:3000/users',data).then((res)=>{
        //   console.log("user added successfully");
        getAllData();
        handleClear();      
      })

   }

  const getAllData=()=>{
    axios.get('http://localhost:3000/users').then((res)=>{
        setUpdate(res.data);
       })
  }

const deleteUser=(dating)=>{
    console.log(dating);
    axios.delete('http://localhost:3000/users/'+dating.id).then(res=>{
        getAllData();
    })
}

这是用于编辑和更新的功能,在这里我可以绑定输入字段,但不能绑定单选和复选框...

 const editUser=(userData)=>{
        setdata(userData)
    }
    
     const handleEdit=()=>{
         console.log(data);
             axios.put('http://localhost:3000/users/'+data.id,data).then(res=>{
            getAllData();
        })
     }
    
        return (
            <React.Fragment>
                <h1>LordShiva</h1>
                <div className="container mt-3">
                    <div className="row">
                        <div className="col-md-6">
                            <div className="card">
                                <div className="card-header bg-success text-white">
                                    <h4>Form</h4>
                                    <form>
                                        <div className="form-group">
                                            <input type="text" className="form-control" placeholder='UserName' name="UserName" value={data.UserName} onChange={handleChange} />
                                        </div>
                                        <div className="form-group">
                                            <input name="phone" className="form-control" placeholder='PhoneNumber' name="PhoneNumber" value={data.PhoneNumber} onChange={handleChange} />
                                        </div>
    
                                        <div className="form-group">
                                            <input name="email" className="form-control" placeholder='Email' value={data.email} onChange={handleChange} />
                                        </div>
                                        <div className="form-group">
                                            <select name="dropDown" value={data.dropDown} onChange={handleChange} className="form-control" >
                                                <option value=""></option>
                                                <option value="Reactjs">ReactJS</option>
                                                <option value="JS">JavaScript</option>
                                                <option value="csCSSs">CSS</option>
                                                <option value="HTML">HTML</option>
                                            </select>
                                        </div>
                                        <div class="form-row">
                                            <div className="form-group col-md-6">
                                                <label className="font-weight-bold">Gender : </label>
                                                <span className="font-weight-bold" > Male <input type="radio" name="gender" value={data.gender} onChange={handleChange}/></span>
                                                <span className="font-weight-bold" >  Female <input type="radio" name="gender" value={data.gender}  onChange={handleChange} /></span>
                                            </div>
                                            <div class="form-check col-md-6">
                                                
                                                        <label class="form-check-label" for="gridCheck">Course</label><br />
                                                <input type="checkbox" value="HTML" name="checking" value={data.checking} onChange={handleChange} /> HTML <br />
                                                <input type="checkbox" value="JavaScript" name="checking" value={data.checking} onChange={handleChange} /> JavaScript <br />
                                                <input type="checkbox" value="ReactJS" name="checking" value={data.checking} onChange={handleChange} /> ReactJS <br />
                                                <input type="checkbox" value="CSS" name="checking" value={data.checking} onChange={handleChange} /> CSS <br />
                                                    
                                            </div>
                                            <div className="form-row">
                                            <button className="btn btn-cyan" type="button" onClick={handleSubmit}>Submit</button>
                                            <button className="btn btn-cyan" type="button" onClick={handleEdit}>UpdateData</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div className="col-md-12">
                            <div className="card mt-5">
                                <div className="card-header blue-gradient text-white">
                                    <h4>FormDetails</h4>
                                    <div>
                                       <div className="row mt-3">
                                           <div className="col">
                                               <div className="table table-hover table-striped text-center table-primary">
                                                    <thead className="bg-dark text-white font-weight-bold">
                                                        <tr>
                                                            <th>UserName</th>
                                                            <th>DropDownValue</th>
                                                            <th>Gender</th>
                                                            <th>CheckboxValue</th>
                                                            <th>EDIT</th>
                                                            <th>DELETE</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                          {
                                                              update.map(emp => {
                                                                  return(
                                                                      <tr>
                                                                        <td>{emp.UserName} </td>
                                                                        <td>{emp.gender}</td>
                                                                        <td>{emp.checking}</td>
                                                                  <td><button className="btn btn-cyan font-weight-bold" onClick={()=>{editUser(emp)}}>Edit</button></td>  
                                                                        <td><button className="btn btn-green font-weight-bold" onClick={()=>{deleteUser(emp)}}>Delete</button></td>  
                                                                      </tr>
                                                                  )
                                                              })
                                                          }
                                                    </tbody>
                                               </div>
                                           </div>
                                       </div>
                                      
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </React.Fragment >
        )
    }

1 个答案:

答案 0 :(得分:1)

将状态更改为

const [data, setdata] = useState({
  UserName: "",
  dropDown: "",
  gender: null,
  checking: []
});

更新处理程序以访问单选和复选框id属性

const handleChange = (e) => {
  if (e.target.name !== "gender" && e.target.name !== "checking") {
    setdata({ ...data, [e.target.name]: e.target.value });
  } else if (e.target.name === "gender") {
    let allgenders = document.getElementsByName("gender");
    allgenders.forEach((allradio) => {
      if (allradio.checked) {
        setdata({ ...data, [e.target.name]: e.target.id }); // <-- grab input id
      }
    });
  } else if (e.target.name === "checking") {
    let getallCheckboxes = [];
    let allCheckboxes = document.getElementsByName("checking");
    allCheckboxes.forEach((allchecks) => {
      if (allchecks.checked) {
        getallCheckboxes.push(allchecks.id); // <-- grab checkbox id
      }
    });
    setdata({ ...data, [e.target.name]: getallCheckboxes });
  }
};

更新/添加handleClear以重置状态

handleClear = () => {
  setdata({
    UserName: "",
    dropDown: "",
    gender: null,
    checking: []
  });
};

添加id属性并将value属性更改为checked并传递布尔值

<label className="font-weight-bold">Gender : </label>
<span className="font-weight-bold">
  <label>
    Male
    <input
      id="male"
      type="radio"
      name="gender"
      checked={data.gender === "male"}
      onChange={handleChange}
    />
  </label>
</span>
<span className="font-weight-bold">
  <label>
    Female
    <input
      id="female"
      type="radio"
      name="gender"
      checked={data.gender === "female"}
      onChange={handleChange}
    />
  </label>
</span>

...

<label class="form-check-label" for="gridCheck">
  Course
</label>
<br />
<label>
  <input
    id="HTML"
    type="checkbox"
    name="checking"
    checked={data.checking.includes("HTML")}
    onChange={handleChange}
  />
  HTML
</label>
<br />
<label>
  <input
    id="JavaScript"
    type="checkbox"
    name="checking"
    checked={data.checking.includes("JavaScript")}
    onChange={handleChange}
  />
  JavaScript
</label>
<br />
<label>
  <input
    id="ReactJS"
    type="checkbox"
    name="checking"
    checked={data.checking.includes("ReactJS")}
    onChange={handleChange}
  />
  ReactJS
</label>
<br />
<label>
  <input
    id="CSS"
    type="checkbox"
    name="checking"
    checked={data.checking.includes("CSS")}
    onChange={handleChange}
  />
  CSS
</label>

Edit unable-to-bind-the-radio-button-and-checkbox-data-on-button-click-in-react-hooks