我有一个带标签的输入。标签有一些翻译以及一些变化,这些变化取决于用户所在的页面,因此我将翻译键放在
useState
内以观察更改并通过更改标签文本来对它们做出反应。问题是当我将翻译密钥传递给 useState 并更改语言时, useState 内的文本不会翻译。
我用 ** 标记了有问题的
useState
。
import CloseIcon from "@mui/icons-material/Close";
import SearchIcon from "@mui/icons-material/Search";
import { Box, IconButton, TextField } from "@mui/material";
import { useGetTableData } from "hooks/useGetTableData";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import NumberFilterSelect from "./NumberFilterSelect";
const NumberFilter = () => {
const { refetch, query, isInvoices, findOne } = useGetTableData();
const { t } = useTranslation();
const [Number, setNumber] = useState("");
const handleInputChange = (e) => setNumber(e.target.value);
**const [label, setLabel] = useState(t("invoice.lookup.labelinvoiceNo"));**
const handleLabelChange = (label) => setLabel(label);
const handleFilterByNumber = () => {
if (Number === "") return;
findOne({
customerId: query.customerId,
[`${isInvoices ? "invoiceNumber" : "orderNumber"}`]: Number,
});
};
const clearNumberFilter = () => {
refetch();
setNumber("");
};
return (
<Box
sx={(theme) => ({
display: "flex",
backgroundColor: theme.palette.inputBackgroundColor.main,
border: `1px solid ${theme.palette.inputBorderColor.main}`,
borderRadius: "4px",
"&:hover": {
background: "#e7e7e7",
},
})}
>
<TextField
label={label}
value={Number}
onChange={handleInputChange}
variant="filled"
onKeyDown={(e) => e.key === "Enter" && handleFilterByNumber()}
sx={{
width: "100%",
"& .MuiInputBase-root": {
background: "none",
border: "none",
},
}}
InputLabelProps={{ shrink: true }}
InputProps={{
endAdornment: (
<IconButton onClick={handleFilterByNumber}>
<SearchIcon />
</IconButton>
),
disableUnderline: true,
sx: {
background: "none",
borderRadius: 0,
"&:hover": {
background: "none",
},
},
}}
/>
{isInvoices && (
<NumberFilterSelect handleLabelChange={handleLabelChange} />
)}
<Box
sx={(theme) => ({
display: "flex",
borderLeft: `1px solid ${theme.palette.inputBorderColor.main}`,
})}
>
<IconButton
onClick={clearNumberFilter}
sx={{
"&:hover": {
background: "none",
},
}}
>
<CloseIcon />
</IconButton>
</Box>
</Box>
);
};
export default NumberFilter;
我通过使用useEffect解决了这个问题。我不喜欢这一点,并且很乐意接受其他一些更微妙的解决方案。
useEffect(() => {
setLabel(isInvoices ? labelinvoiceNo : labelorderNo);
}, [isInvoices, labelinvoiceNo, labelorderNo]);