0

//来自触发事件的输入的值在状态中得到更新但没有在浏览器中显示,我不太明白发生了什么,我一直在使用相同的方法来更新我的另一个项目中的状态

import React, { useState } from "react";
    const Register=()=>{

    const [user,setUser]=useState({
        name:"",
        email:"",
        password:"",
        reenterPassword:""
    });
    
    let changeHandler=(e)=>{
        const { name, value } = e.target
        setUser({
            ...user,
            [name]: value
        })
    
    }

    return(
        <div className="register">
            <h1>Register</h1>
            <input onChange={changeHandler}  name="Username" placeholder="Please Enter Your Name" type="text" defaultValue="" value={user.name}/>
            <input onChange={changeHandler} name="Email" placeholder="Enter your Email" type="email" value={user.email}/>
            <input onChange={changeHandler} name="Password" placeholder="Create Your Password" type="password" value={user.password}/>
            <input onChange={changeHandler} name="ReEnterPassword" placeholder="Re-Enter Your Password" type="password" value={user.reenterPassword}/>
            <div className="button">Register</div>
            <div>OR</div>
            <div className="button">Login</div>
        </div>
    )
}
export default Register;


  [1]: https://i.stack.imgur.com/G8beV.png
4

2 回答 2

1

这里有很好的答案:https ://stackoverflow.com/a/58877875/2091359

你不应该像这样使用 useState ,你可以像这样分别为每个输入做 useState :

  const [name, setName] = useState('')

  const handleChangeName = (e) => {
    setName(e.target.value);
  }

  return(
      <div className="register">
          <h1>Register</h1>
          <input onChange={handleChangeName} name="Username" placeholder="Please Enter Your Name" type="text" value={name}/>
          ...

或使用 useReduce

于 2021-09-23T12:13:12.137 回答
1

试试这个代码:

const Register=()=>{
const [user,setUser]=useState({
        Username:"",
        Email:"",
        Password:"",
        ReEnterPassword:""
    });
    
    let changeHandler=(e)=>{
        const { name, value } = e.target
        setUser({
            ...user,
            [name]: value
        })
    }
    return (
          <div className="register">
            <h1>Register</h1>
            <input onChange={(e)=>changeHandler(e)}  name="Username" placeholder="Please Enter Your Name" type="text" defaultValue="" value={user.name}/>
            <input onChange={(e)=>changeHandler(e)} name="Email" placeholder="Enter your Email" type="email" value={user.email}/>
            <input onChange={(e)=>changeHandler(e)} name="Password" placeholder="Create Your Password" type="password" value={user.password}/>
            <input onChange={(e)=>changeHandler(e)} name="ReEnterPassword" placeholder="Re-Enter Your Password" type="password" value={user.reenterPassword}/>
            <div className="button">Register</div>
            <div>OR</div>
            <div className="button">Login</div>
        </div>
      );
}
export default Register;

您也需要为 html 输入属性使用相同的名称,并尝试在 onChange 事件中使用回调。

于 2021-09-23T12:16:55.843 回答