【发布时间】:2023-01-07 19:28:33
【问题描述】:
在.mdx 文件中访问环境变量的最佳方式是什么。
Remix 在普通组件中访问.env 变量的方法是使用加载程序数据挂钩 (useLoaderData())。但是,在.mdx 文件中不能轻易使用钩子。
我还尝试通过父组件的 props 传递环境变量,但这也不起作用,因为我无法弄清楚 Remix 使用哪个库来处理 .mdx 文件。
干杯
【问题讨论】:
在.mdx 文件中访问环境变量的最佳方式是什么。
Remix 在普通组件中访问.env 变量的方法是使用加载程序数据挂钩 (useLoaderData())。但是,在.mdx 文件中不能轻易使用钩子。
我还尝试通过父组件的 props 传递环境变量,但这也不起作用,因为我无法弄清楚 Remix 使用哪个库来处理 .mdx 文件。
干杯
【问题讨论】:
我不知道如何将 props 传递给组件,但我找到了一个比较好的解决方法。我创建了一个 ContactText 组件,其唯一任务是读取 contactConfig 并返回所需的配置属性值。
ContactText.tsx
const ContactText: React.FC<TProps> = (props) => {
const { contactConfig } = useRootContext();
const { contactConfigPath, as, ...rest } = props;
const getValue = React.useCallback((): string => {
const contactConfigPathParts = contactConfigPath.split('.');
let currentValue = contactConfig;
for (const part of contactConfigPathParts) {
if (currentValue != null) {
currentValue = (currentValue as any)[part];
}
}
return typeof currentValue === 'string' ? currentValue : 'unknown';
}, [contactConfig, contactConfigPath]);
return as != null ? (
React.createElement(as, {
children: getValue(),
...rest,
})
) : (
<>{getValue()}</>
);
};
export default ContactText;
type TProps = {
contactConfigPath: string;
as?: React.ElementType;
};
whatever.mdx
// ..
Phone: <ContactText contactConfigPath={'phoneNumber'} />
<ContactText contactConfigPath={'address.postCode'} />
// ..
【讨论】: