Javascript 获取“反应元素”;dir";显示方向值(rtl与ltr)

Javascript 获取“反应元素”;dir";显示方向值(rtl与ltr),javascript,reactjs,Javascript,Reactjs,目标: 创建一个可重用组件,用于检测显示方向并进行相应渲染 我真的希望能够将dir=“rtl”设置在DOM中较高的位置,然后让组件继承该值,并使用该值确定如何进行一些处理以最佳方式显示组件 组件类似于: <div dir="rtl"> <Field label="This is a rtl field..." /> </div> const Field: React.FunctionComponent<FieldProps&

目标:

创建一个可重用组件,用于检测显示方向并进行相应渲染

我真的希望能够将dir=“rtl”设置在DOM中较高的位置,然后让组件继承该值,并使用该值确定如何进行一些处理以最佳方式显示组件

组件类似于:

    <div dir="rtl">
      <Field label="This is a rtl field..." />
    </div>
const Field: React.FunctionComponent<FieldProps> = ({ attributes }) => {
  const divWrapper = React.useRef<HTMLDivElement>(null); // A reference to current component...
  const thisComponentDirection = divWrapper.dir;

  return (
    <div>
        <WarpBasedOnDir condition={thisComponentDirection} wrapper={directionWrapper}>
          <MaterialTextField attributes={attributes} />
        </WarpBasedOnDir>
    </div>
  );
};

显示方式如下:

    <div dir="rtl">
      <Field label="This is a rtl field..." />
    </div>
const Field: React.FunctionComponent<FieldProps> = ({ attributes }) => {
  const divWrapper = React.useRef<HTMLDivElement>(null); // A reference to current component...
  const thisComponentDirection = divWrapper.dir;

  return (
    <div>
        <WarpBasedOnDir condition={thisComponentDirection} wrapper={directionWrapper}>
          <MaterialTextField attributes={attributes} />
        </WarpBasedOnDir>
    </div>
  );
};
const字段:React.FunctionComponent=({attributes})=>{

const divWrapper=React.useRef(null);//对当前组件的引用。。。 const thisComponentDirection=divWrapper.dir; 返回( ); };
问题:

    <div dir="rtl">
      <Field label="This is a rtl field..." />
    </div>
const Field: React.FunctionComponent<FieldProps> = ({ attributes }) => {
  const divWrapper = React.useRef<HTMLDivElement>(null); // A reference to current component...
  const thisComponentDirection = divWrapper.dir;

  return (
    <div>
        <WarpBasedOnDir condition={thisComponentDirection} wrapper={directionWrapper}>
          <MaterialTextField attributes={attributes} />
        </WarpBasedOnDir>
    </div>
  );
};
我找不到这样的版本:

const divWrapper = React.useRef<HTMLDivElement>(null); // A reference to current component...
const thisComponentDirection = divWrapper.dir;

const divWrapper=React.useRef(null);//对当前组件的引用。。。
const thisComponentDirection=divWrapper.dir;
问题:


有没有办法在包装器元素/组件上设置目录,然后让React组件从该组件中找到目录?

由于我没有足够的要点来评论,我将此作为一个答案发布

我想你正在寻找反应状态。退房

如果您使用的是功能组件,则可以使用
useState
hook

如果要将“dir”存储为属性,请尝试

divWrapper.getAttribute('dir');

希望这能有所帮助

我认为使用React contexts()可能是一种更好的方法,可以将属性存储在某个地方,并尝试使用ref.@larz,这是一种方法。。。然而,我想使用组件作为一个重要的库,不需要任何设置,只需要参数。如果我理解正确,我认为这仍然很容易实现。您只需要导出上下文提供者和使用者。将提供程序放在层次结构中相当高的位置,然后放在您想查看其是否设置为
rtl
ltr
的任何位置,导入使用者并包装您将要使用的组件。@larz我的目标是在从我的库引入的组件之外不使用任何特定于框架的方法。我试图切断组件对上下文或道具的依赖,并查看消费者应用程序的DOM中已经存在的内容。我尝试了此方法,但如果在DOM中进一步设置,则似乎找不到dir属性。你知道有没有这样的例子吗?const divWrapper=React.useRef(null);此代码是否返回正确的引用?