Material UI : 如何提取文本字段的值
Material UI : How to extract the value of the text field
如何获取文本字段组件中的用户值。
这是我要填充的表单文本字段值。我正在使用 material ui 并尝试使用钩子和 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);
};
您需要使用状态。
每当 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
如何获取文本字段组件中的用户值。
这是我要填充的表单文本字段值。我正在使用 material ui 并尝试使用钩子和 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);
};
您需要使用状态。
每当 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