在 React Js 中实现 RTL 的正确方法
安装管理 RTL 布局所需的软件包:
npm install rtlcss postcss-rtl
使用postcss-rtl进行样式自动转换。
修改您的 CSS 文件以包含诸如 margin-inline-start 之类的逻辑属性,并避免硬编码的左/右样式。
在你的项目中添加 PostCSS 配置:
// postcss.config.js module.exports = { plugins: { 'postcss-rtl': {}, }, };
`const isRTL = (lang) => ['ar', 'he'].includes(lang);
document.documentElement.dir = isRTL(语言) ? 'rtl' : 'ltr';
`
使用状态管理库(例如 Redux、Context API)在 ltr 和 rtl 之间切换。
使用 Chrome DevTools 强制 RTL 模式进行测试。
通用准则
使用常量进行对齐:定义对齐常量:
const ALIGN_START = isRTL ? 'right' : 'left'; const ALIGN_END = isRTL ? 'left' : 'right';
尽早并经常测试:验证 LTR 和 RTL 布局的 UI 组件。
利用翻译工具:使用谷歌翻译等服务进行初步翻译,并聘请母语人士确保准确性。