问题描述
我有一个看起来像这样的组件: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;
解决方法
我现在自己找到了解决方案。肯定不会是最好的,但它确实有效,因此达到了它的目的:
...
const handleButtonClick = (prop,currentValues) => (event) => {
if (values.password.length < 16 && re.test(event.target.value)) {
setValues({ ...values,[prop]: values.password + event.target.value });
}
};
...