reactjs - React - 将按钮值传递给(mui)文本字段
问题描述
我有一个看起来像这样的组件: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 });
}
};
...
推荐阅读
- c++ - 为什么make_pair
在 C++ 11 中失败? - javascript - React - 更全面的电子邮件验证
- java - 防止 Jersey 在注入参数时关闭 InputStream?
- google-data-studio - 有没有办法自动创建具有不同数据源的 Data Studio 报告
- javascript - 设置一个变量等于多个名称
- apache-kafka - hadoop + kafka集群中的2个zookeper服务器集群-可能吗?
- angularjs - 使用angularjs更改输入字段中的日期时间格式
- java - 如何在一个合成中使用两个网格布局
- javascript - HTML CSS:使用带有 SVG 图标的可折叠切换
- java - java流映射对象参数到hashset