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

时间:2019-09-03 12:56:18

标签: reactjs localization react-intl

因此,这是我的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? / p>

1 个答案:

答案 0 :(得分:1)

您需要将状态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)
相关问题