我使用 MUI Data Grid froa 表,现在我正在从事 i18n 本地化工作。我遇到了一个问题,我无法翻译列标题,因为它们是静态对象而不是反应组件。应用 t hook 不适用于语言更改。触发语言更改时如何更改翻译?
这是我导出到表反应组件文件并在列道具中使用的文件。
import { Box, Tooltip } from "@mui/material";
import {
deliverTruckBulk,
pickupTruckBulk,
} from "assets/img/statuses/statusImages";
import { dateComparator, localizeDate, localizeTime } from "helpers/helpers";
import i18next from "i18next";
import StatusIcon from "../../../../StatusIcon/StatusIcon";
import {
OrderTableCaption,
OrderTableText,
} from "../../../../Typography/OrderList";
// const t = (string) => i18next.t(string);
export const OrderTableColumns = [
{
field: "shippingDate",
headerName: "Requested Date",
sortComparator: dateComparator,
renderCell: (params) => (
<Box>
<OrderTableText sx={{ fontWeight: 500 }}>
{localizeDate(params.value.date)}
</OrderTableText>
<OrderTableCaption>
{`${localizeTime(params.value.startTime)} - ${localizeTime(
params.value.endTime
)}`}
</OrderTableCaption>
</Box>
),
flex: 0,
},
{
field: "po-order",
headerName: i18next.t("order.orderNumber"),
renderCell: (params) => (
<Box>
<OrderTableText>{params.value.customerReference}</OrderTableText>
<OrderTableCaption>{params.value.orderNumber}</OrderTableCaption>
</Box>
),
flex: 1,
sortable: false,
},
{
field: "destination",
headerName: "Destination",
renderCell: (params) => (
<Box sx={{ display: "flex", flexDirection: "column" }}>
<OrderTableText>{params.value.siteName}</OrderTableText>
<OrderTableCaption>{params.value.street}</OrderTableCaption>
</Box>
),
flex: 1,
sortable: false,
},
{
field: "material",
headerName: "Material",
renderCell: (params) => <OrderTableText>{params.value}</OrderTableText>,
flex: 1,
sortable: false,
},
{
field: "ordered-delivered",
headerName: "Ordered/Delivered",
renderCell: ({ value }) => {
const isShippingTypeCollect = value.shippingType === "collect";
const shippingType = isShippingTypeCollect
? pickupTruckBulk
: deliverTruckBulk;
const tooltipTitle = `${
isShippingTypeCollect ? "Pick-up" : "Delivery"
} by bulk carrier`;
return (
<Box sx={{ display: "flex", columnGap: "5px" }}>
<OrderTableText>
{value.quantity} {i18next.t("capacityTons1")}
</OrderTableText>
<Tooltip title={tooltipTitle}>
<img src={shippingType} alt={shippingType} width="24px" />
</Tooltip>
</Box>
);
},
flex: 0,
sortable: false,
},
{
field: "status",
headerName: i18next.t("order.orderStatus"),
renderCell: (params) => <StatusIcon status={params.value} />,
flex: 0,
maxWidth: 60,
sortable: false,
},
];
将列对象移动到自定义挂钩中,我可以从 i18n 访问 t 挂钩。需要进一步重构,但至少它可以工作。