我的代码上有一些输入掩码,一个按钮网格,我有一个状态来存储选择了哪个按钮,我想根据选择的按钮更改应用于输入的掩码。
状态:
const [selectedButton, setSelectedButton] = React.useState("");
我试过这个:
const [input, setInput] = useMask(
selectedButton === "Key1" ? maskOne : maskTwo
);
它工作得很好!但只有2个掩码,我有4个不同的掩码,我需要一些开关盒类型的结构来选择应用的掩码
好吧,您或多或少已经提出了解决方案。
const [selectedButton, setSelectedButton] = React.useState("");
const returnMask = (button) => {
switch (button) {
case "Key1":
return maskOne
case "Key2":
return maskTwo
case "Key3":
return maskThree
case "Key4":
return maskFour
default:
return maskOne
}
}
const [input, setInput] = useMask(
returnMask(selectedButton)
);
或者,如果可以重命名遮罩或重命名设置为selectedButton
的值,则可以简单地按值引用元素。
const [selectedButton, setSelectedButton] = React.useState("");
const [input, setInput] = useMask([selectedButton]);
// Rename ether `Key1`, `Key2` to `maskOne` or `maskTwo`, or do it the opposite way (renaming the masks)