作者:
    Creation:2025-07-27Last update:2025-07-27

    基于性别的内容 / Intlayer 中的性别

    性别的工作原理

    在 Intlayer 中,基于性别的内容是通过 gender 函数实现的,该函数将特定的性别值('male','female')映射到相应的内容。此方法使您能够根据给定的性别动态选择内容。当与 React Intlayer 或 Next Intlayer 集成时,会根据运行时提供的性别自动选择适当的内容。

    设置基于性别的内容

    要在您的 Intlayer 项目中设置基于性别的内容,请创建一个包含性别特定定义的内容模块。以下是各种格式的示例。

    **/*.content.ts
    import { gender, type Dictionary } from "intlayer";
    
    const myGenderContent = {
      key: "my_key",
      content: {
        myGender: gender({
          male: "针对男性用户的内容",
          female: "针对女性用户的内容",
          fallback: "未指定性别时的内容", // 可选
        }),
      },
    } satisfies Dictionary;
    
    export default myGenderContent;
    如果未声明回退内容,当性别未指定或不匹配任何定义的性别时,将使用最后声明的键作为回退内容。

    在 React Intlayer 中使用基于性别的内容

    To utilize gender-based content within a React component, import and use the useIntlayer hook from the react-intlayer package. This hook fetches the content for the specified key and allows you to pass in a gender to select the appropriate output.

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const GenderComponent: FC = () => {
    const { myGender } = useIntlayer("my_key");
    
    return (
      <div>
        <p>
          {
            /* Output: my content for male users */
            myGender("male")
          }
        </p>
        <p>
          {
            /* Output: my content for female users */
            myGender("female")
          }
        </p>
        <p>
          {
            /* Output: my content for male users */
            myGender("m")
          }
        </p>
        <p>
          {
            /* Output: my content for female users */
            myGender("f")
          }
        </p>
        <p>
          {
            /* Output: my content when gender is not specified */
            myGender("")
          }
        </p>
        <p>
          {
            /* Output: my content when gender is not specified */
            myGender(undefined)
          }
        </p>
      </div>
    );
    };
    
    export default GenderComponent;

    附加资源

    有关配置和使用的更详细信息,请参阅以下资源:

    这些资源提供了关于在各种环境和框架中设置和使用 Intlayer 的更多见解。