材质用户界面:如何提取文本字段的值

时间:2019-09-05 17:41:09

标签: reactjs authentication frontend material-ui textfield

如何在文本字段组件中获取用户值。

这是我要填充的表单文本字段值。我正在使用材质ui并尝试使用hooks和useEffect以获得所需的结果。

<TextField
             variant="outlined"
             margin="normal"
             required
             fullWidth
             name="password"
             label="Password"
             type="password"
             id="password"
             autoComplete="current-password"
             autoFocus
           />
<FormControlLabel
             control={<Checkbox value="remember" color="primary" />}
             label="Remember me"
           />
           <Button
             type="submit"
             fullWidth
             variant="contained"
             color="primary"
             className={classes.submit}
             onClick={handleClick}
           >
             Sign In
           </Button>
</form>



How can I get the password in alert/console log on handleClick. 

const handleClick = () => {
   console.log(password);
 };

1 个答案:

答案 0 :(得分:0)

您需要使用State。
每当TextField的值更改时,就将其保存为组件状态。 单击提交时,您可以访问状态:

const TextFieldWithState = () => {
  const [password, setPassword] = useState('');

  const handleClick = () => {
    console.log(password);
  };

  return (
    <form>
      <TextField
        variant="outlined"
        margin="normal"
        required
        fullWidth
        name="password"
        label="Password"
        type="password"
        id="password"
        autoComplete="current-password"
        autoFocus
        value={password}
        onChange={(event) => {setPassword(event.target.value)}} //whenever the text field change, you save the value in state
       />
      <FormControlLabel
        control={<Checkbox value="remember" color="primary" />}
        label="Remember me"
      />
      <Button
        type="submit"
        fullWidth
        variant="contained"
        color="primary"
      //  className={classes.submit}
        onClick={handleClick}
      >
        Sign In
      </Button>
  </form>
  );
};

您可以了解有关useState钩子here

的更多信息