【问题标题】:React-Admin DateField, DateInput locale globalReact-Admin DateField,DateInput locale global
【发布时间】:2020-04-28 08:55:01
【问题描述】:

React admin 允许您在使用 DateFieldDateInput 时在组件中设置日期区域设置。

<DateField source="publication_date" locales="fr-FR" />
// renders the record { id: 1234, publication_date: new Date('2017-04-23') } as
<span>23/04/2017</span>

但大多数时候我们不需要在组件上设置它,而是需要全局配置它。有没有办法全局设置?

我尝试设置 i18n 提供程序的默认 locale,但看起来它只考虑用于翻译而不考虑日期格式。

我也尝试过覆盖Date.toLocaleDateString(),但效果不佳。

【问题讨论】:

    标签: javascript reactjs localization react-admin


    【解决方案1】:

    你可以使用 useLocale 钩子,它返回 react-admin 的 i18nProvider 当前语言环境,默认为 'en'

    https://marmelab.com/react-admin/Translation.html#uselocale-getting-the-current-locale

    假设这是一个 Show 视图:

    import { useLocale } from 'react-admin'
    
    export const ResourceShow = props => {
    
        const locale = useLocale()
    
        return (
            <Show {...props}>
                <SimpleShowLayout>
                    <DateField source="publication_date" locales={locale} />
                </SimpleShowLayout>
            </Show>
        )
    }
    

    如果你真的想覆盖 Date.toLocaleDateString,不推荐这样做,你可以这样做:

    Date.prototype.toLocaleDateString = customFunc
    

    顺便说一句,我同意 DateField 默认使用 i18nProvider 语言环境。

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 2015-01-08
      相关资源
      最近更新 更多