【发布时间】:2021-05-15 00:28:01
【问题描述】:
我有一个看起来像这样的组件:PIN-Component
我想要的:单击按钮后,按钮的值应出现在文本字段中。 文本字段来自 Material-UI-library。
目前输入仅适用于键盘。 当我单击一个按钮时,它的值会出现在输入中,但只要我按下它或另一个按钮,该字段就会重置,可以说,只有新值出现。
这是我目前得到的代码:
import React, { useState } from "react";
//all other imports for icons, the text-field etc.
//----------------------------------------------
const useStyles = makeStyles((theme) => ({
root: {
display: "flex",
flexWrap: "wrap"
},
margin: {
margin: theme.spacing(1)
},
withoutLabel: {
marginTop: theme.spacing(3)
},
textField: {
width: "250px"
}
}));
function X1Pin() {
const re = /^[0-9\b]+$/;
const classes = useStyles();
const [values, setValues] = useState({
password: "",
showPassword: false
});
const handleChange = (prop) => (event) => {
if (values.password.length < 16 && re.test(event.target.value)) {
setValues({ ...values, [prop]: event.target.value });
}
console.log(event.target.value); //values in inputField
};
const handleClickShowPassword = () => {
setValues({ ...values, showPassword: !values.showPassword });
};
const handleMouseDownPassword = (event) => {
event.preventDefault();
};
const handleButtonClick = (prop) => (event) => {
if (values.password.length < 16 && re.test(event.target.value)) {
setValues({ ...values, [prop]: event.target.value });
}
};
return (
<>
<div className="buttonTable">
<div className={classes.root}>
<div>
<FormControl
className={clsx(classes.margin, classes.textField)}
variant="outlined"
>
<InputLabel htmlFor="outlined-adornment-password">
PIN-Input
</InputLabel>
<OutlinedInput
id="outlined-adornment-password"
type={values.showPassword ? "text" : "password"}
value={values.password}
onChange={handleChange("password")}
endAdornment={
<InputAdornment position="end">
<IconButton
aria-label="toggle password visibility"
onClick={handleClickShowPassword}
onMouseDown={handleMouseDownPassword}
edge="end"
>
{values.showPassword ? <Visibility /> : <VisibilityOff />}
</IconButton>
</InputAdornment>
}
labelWidth={75}
/>
</FormControl>
</div>
</div>
<table>
<tr>
<td>
<button
className="btn--pin"
value="1"
onClick={handleButtonClick("password")}
>
1
</button>
</td>
//all other buttons with the same pattern
</table>
</div>
</>
);
}
export default X1Pin;
【问题讨论】:
标签: reactjs button onclick material-ui textfield