{translation1} {translation2} {translation3}
; } ``` ### 句子碎片化 你可以使用 `derive` 通过函数调用处理句子碎片化。 ```jsx copy import { derive, gt } from 'gt-next'; function getSubject(gender) { return gender === 'male' ? 'boy' : 'girl'; } function Component({ gender }) { const translation = gt(`The ${derive(getSubject(gender))} is playing.`); return{translation}
; } ``` ### 一致性 没有 `derive` 时,处理一致性的翻译在语法上会很繁琐。 你需要添加一个 select 语句来处理一致性 (如复数、性别等) 。 然后,还必须枚举每一种可能的结果。 ```jsx copy import { gt } from 'gt-next'; function getSubject(gender) { return gender === 'male' ? 'boy' : 'girl'; } function Component({ gender }) { const translation = gt( '{gender, select, boy {The boy is playing.} girl {The girl is playing.} other {}}', { gender: getSubject(gender) , }, ); return{translation}
; } ``` 有了 `derive`,处理一致性就变得轻而易举。 无需使用 select 语句,也不必指定每种结果。 ```jsx copy import { derive, declareVar, gt } from 'gt-next'; function getSubject(gender) { return gender === 'male' ? 'boy' : 'girl'; } function Component({ gender }) { const translation = gt(`The ${derive(getSubject(gender))} is playing.`); return{translation}
; } ``` 使用 `derive` 后,CLI 工具会识别出 `getSubject` 有两种可能的结果,并为每种结果创建一个翻译条目。 这样就能自动处理一致性。 * "The boy is playing" -> "*El* niño está jugando" * "The girl is playing" -> "*La* niña está jugando" ### 配合变量使用 你可以将 `derive` 与 `declareVar` 结合使用,以支持动态内容。 ```jsx copy import { derive, declareVar, gt } from 'gt-next'; function getGreeting(name) { return name ? `Hello, ${declareVar(name)}` : 'Hello, stranger'; } function Component({ name }) { const translation = gt(`${derive(getGreeting(name))}! How are you?`); return{translation}
; } ``` ### 复杂函数 函数可以包含多个条件分支和 return 语句。 ```jsx copy import { derive, gt } from 'gt-next'; function getStatusMessage(status, priority) { if (status === 'complete') { return priority === 'high' ? 'Urgent task completed' : 'Task completed'; } else if (status === 'pending') { return priority === 'high' ? 'Urgent task pending' : 'Task pending'; } return 'Task status unknown'; } function Component({ status, priority }) { const message = gt(`${derive(getStatusMessage(status, priority))}.`); return{message}
; } ``` ### 内联表达式与逻辑 你可以直接在 `derive` 调用中嵌入逻辑。 ```jsx copy import { derive, gt } from 'gt-next'; function Component({ gender }) { const message = gt(`The ${derive(gender === 'male' ? 'boy' : 'girl')} is playing.`); return{message}
; } ``` *** ## 注意事项 * 请谨慎使用 `derive`,因为它可能会使翻译条目呈指数级增长 * 所有可能的结果都必须能在构建时被静态分析 * 静态函数中的变量应使用 `declareVar` 包装 ## 后续步骤 * 如需在静态函数中标记动态内容,请参阅 [`declareVar`](/docs/next/api/strings/declare-var) * 如需从已声明的变量中提取原始值,请参阅 [`decodeVars`](/docs/next/api/strings/decode-vars) * 关于对应的 JSX 形式,请参阅 [`