简体   繁体   中英

ı am trying to make javascript form project. with react. I want put onChange function to inside of input. But how?

I am trying to make form project with react but ı have a problem. when ı click to enter button, the button give true to console. even the form has not complete. So ı want ıf form ıs not complete or give error, the enter button give false to console. else, enter button give true to console. But ı have to do with onChange. So how can ı do with onChange this?

    import React from "react";
import { useState } from "react";

const Contact = () => {
    const [button, setbutton] = useState(false);
    
    const buttonOnClick = () => {
        setbutton(true)
        console.log(`Form submitted, ${button}`);    
    }


    console.log(button);

    return(
<div className="main">
    <form >
    <div className="baslik">
     <div className="container center">
    <h1>Contact Form</h1>
    </div>
    </div>
        <div className="field" >
           <label className="text"> Name And Surname: </label>
           <input className="form" placeholder="Kerem Kurt" required />
        </div>
    

      <button type="submit" className="button" onClick ={() => buttonOnClick()}> Enter </button> 

React doesn't care if your form is complete or not. You clicked the button and it executed the onClick handler. If you want to print false. Please validate your form in onButtonClick() and then use setbutton appropriately. Ie if you find that your form is invalid set it to false or else set it to true.

You have to manually do that. As you are not using any form validation library. Let me give you an example

 import React from "react"; import { useState } from "react"; const Contact = () => { const [button, setbutton] = useState(false); const [inputValue,setInputValue] = useState("") const buttonOnClick = () => { if(inputValue === ""){ setbutton(false) }else{ setbutton(true) } console.log(`Form submitted, ${button}`); } console.log(button); return( <div className="main"> <form> <div className="baslik"> <div className="container center"> <h1>Contact Form</h1> </div> </div> <div className="field" > <label className="text"> Name And Surname: </label> <input className="form" placeholder="Kerem Kurt" required value={inputValue} onChange={(e)=>setInputValue(e.target.value)/> </div> <button type="submit" className="button" onClick ={() => buttonOnClick()}> Enter </button> </form> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM