【问题标题】:change locale moment js更改语言环境时刻 js
【发布时间】:2019-12-05 07:37:16
【问题描述】:

如何更改日期本地化并显示新的本地化日期?

const Locale = () => {
  return (
    <div>
      <button onClick={() => moment.locale("en")}>English</button>
      <button onClick={() => moment.locale("de")}>German</button>
      <p>{moment().format("LLLL")}</p>
    </div>
  );
};

codesandbox 示例https://codesandbox.io/s/vigorous-violet-v0hvf

【问题讨论】:

    标签: reactjs momentjs


    【解决方案1】:

    这是一个带有工作示例的代码框https://codesandbox.io/s/peaceful-lumiere-97yto

    如果您希望组件再次重​​新渲染,您应该对状态进行一些更改。

    【讨论】:

      【解决方案2】:
      const deMoment = moment().locale("de").format("LLLL");
      const enMoment = moment().locale("en").format("LLLL");
      const Locale = () => {
        const [momentDate, setMomentDate] = useState(deMoment);
      
        useEffect(() => {}, [momentDate]);
        return (
          <div>
            <button onClick={() => setMomentDate(enMoment)}>English</button>
            <button onClick={() => setMomentDate(deMoment)}>German</button>
            <p>{momentDate}</p>
          </div>
        );
      };
      

      【讨论】:

        【解决方案3】:

        Moment.js 语言环境只会应用于更新后创建的新实例。因此,我将语言环境保持在状态,并在单击按钮时不断更新它。

        import React, { useState } from "react";
        import moment from "moment";
        
        const Locale = () => {
          let [loc, updateLoc]= useState("en")
          return (
            <div>
              <button onClick={() => updateLoc("en")}>English</button>
              <button onClick={() => updateLoc("de")}>German</button>
              <p>{moment.locale(loc) && moment().format("LLLL")}</p>
            </div>
          );
        };
        
        export default Locale;
        
        

        【讨论】:

          【解决方案4】:

          您必须通知moment 对象的区域设置已更新。

          const Locale = () => {
            const [currentMoment, setCurrentMoment] = useState(moment().format("LLLL"));
            const updateMomentEN = () => {
              moment.locale("en");
              setCurrentMoment(moment().format("LLLL"));
            };
            const updateMomentDE = () => {
              moment.locale("de");
              setCurrentMoment(moment().format("LLLL"));
            };
            return (
              <div>
                <button onClick={updateMomentEN}>English</button>
                <button onClick={updateMomentDE}>German</button>
                <p>{currentMoment}</p>
              </div>
            );
          };
          

          每次更新语言环境后,我们都会根据新的语言环境更新currentMoment。然后useState 进行通知工作。

          【讨论】:

            猜你喜欢
            • 2016-11-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-21
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多