React 中的从右到左 (RTL) 支持 [英] Right to left (RTL) support in React
问题描述
在 React 应用程序中实现 RTL 支持的最佳方式是什么?有没有办法覆盖默认的 <p>
和 <span>
标签(组件)来添加 RTL 支持,这样我就不必重写我已经存在的组件写有RTL支持?(例如,要拥有一些全局变量 window.RTL
,所以当设置为 true 以拥有所有 和
> 标签将文本方向翻转为 RTL).我可能会更改构建系统,或者制作一个 babel 插件,它将用我自己的 ap 标签实现替换所有
React.createElement("p" ...)
,但是有没有更好的解决方案?
谢谢.
更好的方法是使用 CSS/HTML 功能:
direction
CSS 属性- Unicode 符号
‏
/‎
- 将
.rtl
/.ltr
类附加到body
并使用它们来更改顺序
在这种情况下,您的元素在 HTML 中的顺序对于 RTL 和 LTR 是相同的.应用 CSS 规则的差异.
如果你真的需要 React 中元素的顺序,你可以创建自己的组件,如果 RTL 来反转孩子的列表:
const Dir = React.createClass({渲染:函数(){让孩子 = (this.props.direction == 'rtl' && this.props.children && this.props.children.reverse) ?this.props.children.reverse() : null;返回 { 孩子们 };}});//并用作://方向变量 = 'rtl'|'ltr'<方向={方向变量}><a>第一个</a><a>第二个</a><a>第三</a></目录>
What would be the best way to implement RTL support in React apps? Is there a way to override default <p>
and <span>
tags (components) to add RTL support so that I don't have to rewrite components I already wrote to have RTL support? (for example, to have some global variable window.RTL
, so when set to true to have all <p>
and <span>
tags flip text direction to RTL). I could probably change the build system, or make a babel plugin, that will replace all React.createElement("p" ...)
with my own implementation of a p tag, but is there a better solution?
Thanks.
A more optimal way is to use CSS / HTML abilities for that:
direction
CSS property- Unicode symbols
‏
/‎
- Attach
.rtl
/.ltr
classes tobody
and use them to change order
In that cases order of your elements in HTML are the same for RTL and LTR. The difference in applied CSS rules.
If you really need the order of elements in React, you can create own component that reverses the list of children if RTL:
const Dir = React.createClass({
render: function() {
let children = (this.props.direction == 'rtl' && this.props.children && this.props.children.reverse) ? this.props.children.reverse() : null;
return <div>
{ children }
</div>;
}
});
// And use as:
// directionVariable = 'rtl'|'ltr'
<Dir direction={ directionVariable }>
<a>First</a>
<a>Second</a>
<a>Third</a>
</Dir>
这篇关于React 中的从右到左 (RTL) 支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!