因此,这是我的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>
答案 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)