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



所以,这是我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>)

如何在Game的子组件中读取IntlProvider父组件中localeset 的当前值,并相应地设置属性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>
)

更新

另一种方法是用injectIntlHOC 包装您的组件。

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)

最新更新