亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React 如何獲取和觀察正文方向

React 如何獲取和觀察正文方向

犯罪嫌疑人X 2023-05-11 14:13:47
所以我正在構建一個需要支持文本方向(ltr和rtl)的組件在主頁面中,我們使用簡單的 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 中獲取當前主體方向2/ 我有一個改變方向的按鈕,基本上,它會改變 的dir屬性div wrapper,如何確保當它改變時,Slider組件也會更新。
查看完整描述

1 回答

?
SMILET

TA貢獻1796條經驗 獲得超4個贊

動態獲取dir取決于您的狀態管理方法(道具傳播、上下文、mobx、redux 等)。


這是一個簡單的道具傳播方法的例子。


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來檢測道具的變化并相應地更新狀態。


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();

}, []);

查看完整回答
反對 回復 2023-05-11
  • 1 回答
  • 0 關注
  • 191 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號