【问题标题】:Is there any way to access the current locale with React-Intl?有没有办法使用 React-Intl 访问当前的语言环境?
【发布时间】:2017-12-27 17:04:48
【问题描述】:

我想知道是否有任何方法可以使用 React-Intl 访问当前设置的语言环境?

假设我创建了这个:

render() {
  return (
    <IntlProvider locale="en">
      <App>
    </IntlProvider>
  );
}

在 App 中,我想做这样的事情,以访问我传递给 IntlProvider 的语言环境

this.props.locale

有什么办法可以做这样的事情吗?

谢谢。

【问题讨论】:

    标签: javascript reactjs react-native react-intl


    【解决方案1】:

    新答案 - 使用钩子(原文见下文)

    import { useIntl } from 'react-intl';
    
    const MyComponent: FC = () => {
        const intl = useIntl()
        return <div>{`Current locale: ${intl.locale}`}</div>
    }
    
    export default MyComponent
    

    旧答案

    您可以通过简单地从 React Intl 的“注入 API”访问应用程序的任何组件中的当前语言环境:

    import {injectIntl, intlShape} from 'react-intl';
    
    const propTypes = {
      intl: intlShape.isRequired,
    };
    
    const MyComponent = ({intl}) => (
      <div>{`Current locale: ${intl.locale}`}</div>
    );
    
    MyComponent.propTypes = propTypes
    
    export default injectIntl(MyComponent);
    

    【讨论】:

    • 差不多 2 年后,我们现在有一个钩子可以做到这一点@pierre 你想更新你的答案吗?你可以const intl = useIntl(); console.log(intl.locale)
    • 嗨@Bruford,谢谢你。我很乐意更新我的答案,但我必须承认我还没有练习过钩子(我目前正在研究其他堆栈)。你能用钩子把更新的答案发给我吗?
    • 你甚至可以这样做: const {locale} = useIntl()
    【解决方案2】:

    是的,如果您想在任何子组件中访问当前语言环境,最好的方法是读取 context,因为 IntlProvider 提供了一个上下文。 在您的应用程序或任何其他组件中定义您要访问的上下文:

    App.contextTypes = {
        intl: PropTypes.object
    };
    

    现在您可以读取组件中的当前语言环境,例如:

    render() {
        return (
            <div>{this.context.intl.locale}</div>
        )
    }
    

    【讨论】:

    • injectIntl 是访问intl 对象的一种更简洁的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多