【问题标题】:React How to get and watch for body text direction反应如何获取和观察正文方向
【发布时间】:2021-01-28 13:19:12
【问题描述】:

所以我正在构建一个需要同时支持text directionltrrtl)的组件

在主页面中,我们使用简单的 HTML 和 CSS 来确定文本方向

<div data-testid="mountNode" id="slider-preview" class="virtual-body" dir="rtl">
   ...element
</div>

但是,在我的 React 组件中,我想监视这个目录,以便在里面进行一些操作

const Slider: FC<SliderProps> = props => {
  let isRTL = false;  // I want this to actually reflect the current direction of the page
  return (<div>{isRTL} ? 'RTL' : 'LTR' </div>)
}

所以我的问题是

1/ 如何在javascript中获取当前body方向

2/我有一个改变方向的按钮,基本上会改变div wrapperdir属性,如何确定什么时候改变,Slider组件也更新了.

谢谢

【问题讨论】:

  • #slider-preview是react渲染的吗?
  • 不是真的,包装器只是一个html代码

标签: javascript reactjs typescript


【解决方案1】:

动态获取dir 取决于您的状态管理方法(props 传播、上下文、mobx、redux 等)。

这是一个简单的 props 传播方法的示例。

function Slider({ dir }) {
  return (
    <div dir={dir}>
    </div>
  );
};

function App() {
  const [dir, setDir] = useState("ltr");
  return (
    <Slider dir={dir} />
  );
}

https://codesandbox.io/s/gallant-sammet-u553m?file=/src/App.js


为了观察dir 的变化(如果它是外部组件),您可以使用 MutationObserver 来检测 props 的变化并相应地更新状态。

const [direction, setDirection] = React.useState(document.body.dir);
React.useEffect(() => {
  const observer = new MutationObserver((mutationsList, observer) => {
    if (mutationsList.some((mutation) => mutation.attributeName === "dir")) {
      setDirection(document.body.dir);
    }
  });
  observer.observe(document.body, {
    attributes: true
  });
  return () => observer.disconnect();
}, []);

一个工作示例:https://codesandbox.io/s/gracious-sanne-uomlk?file=/src/App.tsx

【讨论】:

  • 是的,这就是我如何将目录传递给 Slider,但我的意思是如何在第一位置检测到它
  • 一般可以使用window.getComputedStyle(element).dir查看滑块根元素的direction(比如:jsbin.com/tefidar/edit?html,css,js,console)。您需要使用 ref 才能访问 DOM 元素。但是,我会避免使用代码并努力(在大多数情况下是可能的)使用 css 实现相同的结果。它会为您省去很多麻烦。
  • 我明白你的意思。因为您知道对于 Slider,附加的 css 需要 JS 逻辑(因为滑块的填充条取决于其当前值,而不仅仅是像文本一样改变方向)。我也想做 100% CSS 但没有找到任何线索。
  • ` window.getComputedStyle(element).dir` 不是反应式的,所以就像我在问题2中问的那样,如果我有一个按钮只是直接更改dom的目录,它不会更新我的反应组件。我觉得在问题 2 中做我需要做的事情是完全不可能的,对吧?
  • 你可以给我看你的代码(也许用codesandbox),css非常强大和灵活,所以它毕竟是可能的。关于第二部分,也许您可​​以使用MutationObserver 来观察主体(或包装器元素)的变化并相应地设置本地状态。比如:codesandbox.io/s/gracious-sanne-uomlk?file=/src/App.tsx:210-226
猜你喜欢
  • 2022-06-10
  • 2021-07-08
  • 2019-03-31
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多