react-intl:根据当前语言环境更改 div 方向

react-intl: change div direction based on current locale

所以,这是我的 App 组件:

const App = () => {
  const [lang, setLang] = useState("en");

  return (
    <IntlProvider
      locale={lang}
      key={lang}
      messages={lang == "en" ? englishMessages : arabicMessages}
    >
      <AppBar>
        <LangSwitch
          checked={lang == "en"}
          onChange={() => setLang(lang == "en" ? "ar" : "en")}
        ></LangSwitch>
      </AppBar>
      <Game />
    </IntlProvider>
  );
};
ReactDOM.render(<App />, document.getElementById("root"));

而且,这是我的 Game 组件:

const Game = ()=>
   (<div direction = "???">
     I want to set direction to ltr if current locale is 'en' other wise to 'rtl'
   </div>)

如何读取 locale 的当前值 - 在 IntlProvider 的父组件中设置 - 在 Game 的子组件中设置 属性 direction相应地?

您需要将状态 lang 传递给您的 Game 组件,

<Game lang={lang}/>

你的 Game 组件应该是,

const Game = (props)=> ( //provide props argument here
   <div direction ={props.lang === 'en' ? 'ltr' : 'rtl'}>  //check your condition
     I want to set direction to ltr if current locale is 'en' other wise to 'rtl'
   </div>
)

更新

另一种方法是用 injectIntl HOC 包装你的组件。

import {injectIntl} from 'react-intl';

const Game = ({intl})=> {
  console.log(intl.locale)
  return ( 
   <div direction ={intl.locale === 'en' ? 'ltr' : 'rtl'}>  //check your condition
     I want to set direction to ltr if current locale is 'en' other wise to 'rtl'
   </div>
  )
}

export default injectIntl(Game)