简体   繁体   中英

How to get username and password in a javascript object in ReactJS?

I am unable to get the login credentials in the object, the code below works perfectly fine for other forms

SignIn.js

export default function SignIn(props) {
  const [state, setState] = useState({
    username:'',
    password:''
 });

 const handleSubmit = (event) =>{
  event.preventDefault()

  const loginCredentials = state;

  console.log(loginCredentials)
}



const handleChange = (evt, name)=>{
  const { value } = evt.target;
  setState({
      ...state,
      [name]: value
      
  });
  props.loginHandler()
}

  const classes = useStyles();

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        
        <Typography component="h1" variant="h5">
          Sign in
        </Typography>
        <form className={classes.form} noValidate>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label="username"
            name="name"
            autoComplete="email"
            autoFocus
            onChange={(event)=>handleChange( event, "username")}

          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="Password"
            type="password"
            id="password"
            autoComplete="current-password"
            onChange={(event)=>handleChange( event, "password")}

          />
          
          
          <Button onClick={handleSubmit}
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}

          >
            Sign In
          </Button>
          
        </form>
      </div>
      
    </Container>
  );
}

Moreover can any one guide me how to handle file responses in react, I have an endpoint which has a csv file as a response how can I write the request so that the file starts downloading on the press of a button

If I understand your necessity, you can do this directly in the button onChange event, like this:

onChange={(event) => setName(event.target.value)}

onChange={(event) => setPassword(event.target.value)}

and you can create some state like this: const [values, setValues] = useState({ name: '', password: '' });

...and apply these data in your submit function:

const handleSubmit = () =>{
  setValues({ name, password });
  console.log(values);
}

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