简体   繁体   中英

Can not change default locale of moment.js in react component

I want to change the dafault locale of this component to fr . Here is the component:

import EventEmitter from 'events';
import pt from 'prop-types';
import React from 'react';
import moment from 'moment';

moment.locale("fr");

class Ticker extends EventEmitter {
  tick = () => this.emit('tick');

  constructor(interval) {
    super();
    this.setMaxListeners(0);
    this.once('newListener', () => setInterval(this.tick, interval));
  }
}

const ticker = new Ticker(30000); // 30 sec

export default class TimeDisplay extends React.Component {
  static propTypes = {
    timeStamp: pt.oneOfType([pt.number.isRequired, pt.string.isRequired]),
    className: pt.string,
    timeAgoInTitle: pt.bool,
  };

  refresh = () => this.forceUpdate();

  componentDidMount() {
    ticker.addListener('tick', this.refresh);
  }

  componentWillUnmount() {
    ticker.removeListener('tick', this.refresh);
  }

  render() {
    moment.locale("fr");
    const time = moment(this.props.timeStamp);
    const timeAgo = Math.abs(moment().diff(time)) < 1000 ? 'maintenant' : time.fromNow();
    const timeISO = time.format();

    const title = this.props.timeAgoInTitle ? timeAgo : time.format('lll');
    const contents = this.props.children ? this.props.children : timeAgo;

    return (
      <time className={this.props.className} dateTime={timeISO} title={title}>{contents}</time>
    );
  }
}

As you can see I've set moment.locale("fr"); both after imports and at render but the moment strings are still shown in English. How can I fix it?

add relativeTime in moment.locale , Its better to use moment.locale in componentWillMount rather than render function

 moment.locale('fr', { relativeTime : { future : 'dans %s', past : 'il ya %s', s : 'quelques secondes', m : 'une minute', mm : '%d minutes', h : 'une heure', hh : '%d heures', d : 'un jour', dd : '%d jours', M : 'un mois', MM : '%d mois', y : 'un an', yy : '%d ans' } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM