【问题标题】:Access .env variables in .mdx file | Remix访问 .mdx 文件中的 .env 变量 |混音
【发布时间】:2023-01-07 19:28:33
【问题描述】:

.mdx 文件中访问环境变量的最佳方式是什么。 Remix 在普通组件中访问.env 变量的方法是使用加载程序数据挂钩 (useLoaderData())。但是,在.mdx 文件中不能轻易使用钩子。 我还尝试通过父组件的 props 传递环境变量,但这也不起作用,因为我无法弄清楚 Remix 使用哪个库来处理 .mdx 文件。 干杯

【问题讨论】:

    标签: reactjs remix


    【解决方案1】:

    我不知道如何将 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'} />
    
    // ..
    

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 2023-01-23
      • 2019-12-03
      • 1970-01-01
      • 2019-01-29
      • 2021-08-07
      • 2017-07-26
      • 2021-02-11
      相关资源
      最近更新 更多