为什么上下文变量无法从组件Header.jsx传递到mainPage.js?

huangapple go评论61阅读模式
英文:

Why the context variable failed to pass from componet Header.jsx to mainPage.js

问题

以下是您要翻译的内容:

MainPage.jsx 文件:

I would like the wording used for the layout inside mainPage would change according to the language selected at component Header.jsx. However, change in Header.jsx could not pass to Header.jsx, therefore, noting is changed when clicking on the language selector.

import React, { useState, useEffect } from "react";
import Header from "../Resources/Components/Header";
import Footer from "../Resources/Components/Footer";
import {MainPageContext, useMainPageContext } from "../Resources/Hooks/mainPageContext";

import "./MainPage.css";

const MainPage = () => {

const context = useMainPageContext();
const {
  language,
} = context;

useEffect(() => {
  console.log("is me hi!")
}, [language])

  const [introductionPage, setIntroductionPage] = useState(0);
  console.log("language is", language)

  const renderLanguageSwitch = (language) => {
    switch (language) {
      case 0:
        return ['測試開始', '測試資料採集同意書'];
      case 1:
        return ['Test Start', 'Test Data Collection Agreement']
      default:
        return ['測試開始', '測試資料採集同意書'];
    }
  };

  const renderButtonSwitch = (language) => {
    switch (language) {
      case 0:
        return ['我同意', '我拒絕'];
      case 1:
        return ['I agree', 'I disagree']
      default:
        return ['我同意', '我拒絕'];
    }
  };

  return (
    <div className="MainPage">
      <Header />
      <div
        style={{
          width: "100%",
          height: "100vh",
          backgroundColor: "#F5821F",
          margin: "0",
        }}
      >
        {introductionPage === 0 && (
          <button
            className="testStartBox"
            onClick={() => {
              setIntroductionPage(1);
            }}
          >
            {renderLanguageSwitch(language)[0]}
          </button>
        )}
        {introductionPage !== 0 && (
          <div>
            <div
              className="testDescriptionBox"
              onClick={() => {
                setIntroductionPage(introductionPage + 1);
              }}
            >
               {renderLanguageSwitch(language)[1]}
            </div>
            <div className="testAgreement">

            </div>
            </div>
        )}

        <div
          className="buttonWrapper"
          style={{ display: introductionPage === 1 ? "" : "none" }}
        >
          <button  onClick={() => {
              setIntroductionPage(introductionPage + 1);
            }}> {renderButtonSwitch(language)[0]}</button>
          <button  onClick={() => {
              setIntroductionPage(0);
            }}>{renderButtonSwitch(language)[1]}</button>
        </div>
      </div>
      <Footer />
    </div>
  );
};
export default MainPage;

Header.jsx 文件:

There is a language selector on the component Header.jsx, I would like to change the language, then change the content of MainPage. However, it doesn't work.

import React from "react";
import { useMainPageContext } from "../Hooks/mainPageContext";

const Header = () => {
  const context = useMainPageContext();
const {
  language,
  onSetLanguage,
} = context;

  return (
    <div className="header">
      <h1
        style={{
            display: "flex",
            flexFlow: "row",
            alignItems: "center",
          width: "calc(100% - 10%)",
          height: "4vh",
         
        }}
      >
        <div style={{display:"flex", color: "#F5821F",}}>
         <img src={require("../Images/Logo.png")} style={{width:"50%", height:"7.5%", marginTop:"0vh"}} alt="image name"/>
        <div style={{ top: "0", margin: "0vh", marginLeft:"2vw", width:" 100%", fontSize:"3vw"}}>中心</div>    
        </div>

        <div><div style={{marginTop:"1vh", fontSize:"2vw"}} onClick={() => {language===1? onSetLanguage(0):onSetLanguage(1);
        }}>繁體/ English</div></div>
      </h1>
     
    </div>
  );
};
export default Header;
英文:

I would like the wording used for the layout inside mainPage would change according to the language selected at component Header.jsx. However, change in Header.jsx could not pass to Header.jsx, therefore, noting is changed when clicking on the language selector.

import React, { useState, useEffect } from &quot;react&quot;;
import Header from &quot;../Resources/Components/Header&quot;;
import Footer from &quot;../Resources/Components/Footer&quot;;
import {MainPageContext, useMainPageContext } from &quot;../Resources/Hooks/mainPageContext&quot;;
import &quot;./MainPage.css&quot;;
const MainPage = () =&gt; {
const context = useMainPageContext();
const {
language,
} = context;
useEffect(()=&gt;{
console.log(&quot;is me hi!&quot;)
},[language])
const [introductionPage, setIntroductionPage] = useState(0);
console.log(&quot;language is&quot;, language)
//const [language, setLanguage]= useState(0);
//below is the script of the test description. 隨時可以加入新array做新language。
const renderLanguageSwitch= (language) =&gt; {
switch(language) {
case 0:
return [&#39;測試開始&#39;,&#39;測試資料採集同意書&#39;];
case 1:
return [&#39;Test Start&#39;, &#39;Test Data Collection Agreement&#39;]
default:
return [&#39;測試開始&#39;,&#39;測試資料採集同意書&#39;];
}
};
const renderButtonSwitch= (language) =&gt; {
switch(language) {
case 0:
return [&#39;我同意&#39;, &#39;我拒絕&#39;];
case 1:
return [&#39;I agree&#39;, &#39;I disagree&#39;]
default:
return [&#39;我同意&#39;, &#39;我拒絕&#39;];
}
};
return (
&lt;div className=&quot;MainPage&quot;&gt;
&lt;Header /&gt;
&lt;div
style={{
width: &quot;100%&quot;,
height: &quot;100vh&quot;,
backgroundColor: &quot;#F5821F&quot;,
margin: &quot;0&quot;,
}}
&gt;
{introductionPage === 0 &amp;&amp; (
&lt;button
className=&quot;testStartBox&quot;
onClick={() =&gt; {
setIntroductionPage(1);
}}
&gt;
{renderLanguageSwitch(language)[0]}
&lt;/button&gt;
)}
{introductionPage !== 0 &amp;&amp; (
&lt;div&gt;
&lt;div
className=&quot;testDescriptionBox&quot;
onClick={() =&gt; {
setIntroductionPage(introductionPage + 1);
}}
&gt;
{renderLanguageSwitch(language)[1]}
&lt;/div&gt;
&lt;div className=&quot;testAgreement&quot;&gt;
&lt;/div&gt;
&lt;/div&gt;
)}
&lt;div
className=&quot;buttonWrapper&quot;
style={{ display: introductionPage === 1 ? &quot;&quot; : &quot;none&quot; }}
&gt;
&lt;button  onClick={() =&gt; {
setIntroductionPage(introductionPage + 1);
}}&gt; {renderButtonSwitch(language)[0]}&lt;/button&gt;
&lt;button  onClick={() =&gt; {
setIntroductionPage(0);
}}&gt;{renderButtonSwitch(language)[1]}&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;{&quot; &quot;}
&lt;Footer /&gt;
&lt;/div&gt;
);
};
export default MainPage;

There is a language selector on the component Header.jsx, I would like to change the language, then change the content of MainPage. However, it doesn't work.

import React from &quot;react&quot;;
import { useMainPageContext } from &quot;../Hooks/mainPageContext&quot;;
const Header = () =&gt; {
const context = useMainPageContext();
const {
language,
onSetLanguage,
} = context;
return (
&lt;div className=&quot;header&quot;&gt;
&lt;h1
style={{
display: &quot;flex&quot;,
flexFlow:&quot;row&quot;,
alignItems:&quot;center&quot;,
width: &quot;calc(100% - 10%)&quot;,
height: &quot;4vh&quot;,
}}
&gt;
&lt;div style={{display:&quot;flex&quot;, color: &quot;#F5821F&quot;,}}&gt;
&lt;img src={require(&quot;../Images/Logo.png&quot;)} style={{width:&quot;50%&quot;, height:&quot;7.5%&quot;, marginTop:&quot;0vh&quot;}} alt=&quot;image name&quot;/&gt;
&lt;div style={{ top: &quot;0&quot;, margin: &quot;0vh&quot;, marginLeft:&quot;2vw&quot;, width:&quot; 100%&quot;, fontSize:&quot;3vw&quot;}}&gt;中心&lt;/div&gt;    
&lt;/div&gt;
&lt;div&gt;&lt;div style={{marginTop:&quot;1vh&quot;, fontSize:&quot;2vw&quot;}} onClick={()=&gt;{language===1? onSetLanguage(0):onSetLanguage(1);
}}&gt;繁體/ English&lt;/div&gt;&lt;/div&gt;
&lt;/h1&gt;
&lt;/div&gt;
);
};
export default Header;

答案1

得分: 0

以下是您要翻译的代码部分:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n
  .use(initReactI18next)
  .init({
    backend: {
        loadPath: `/locales/{{lng}}/translation.json`,
        parse: data => data,
      },
    lng: 'en',
    fallbackLng: 'en',
    debug: true,
    resources: {
      'en': {
        translation: 'en',
      },
      'tw': {
        translation: 'tw',
      },
    },
   
    interpolation: {
      escapeValue: false
    }
  });

export default i18n;

import React , { Component, Suspense , useState, useCallback} from 'react';
import { useTranslation, withTranslation, Trans ,I18nextProvider} from 'react-i18next;

import ReactDOM from "react-dom/client";
import{
  createBrowserRouter, RouterProvider, BrowserRouter as Router
} from "react-router-dom";
import logo from './logo.svg';
import './App.css';

//Import the pages
import MainPage from "./MainPage/MainPage";
import A1SubjectPage1 from "./ASubject/A1SubjectPage1";
import B1ResearcherPage1 from "./BResearcher/B1ResearcherPage1";
import Header from './Resources/Components/Header';

// use hoc for class based components

class LegacyWelcomeClass extends Component {
  render() {
    const { t } = this.props;
    return <h2>{t('title')}</h2>;
  }
}
const Welcome = withTranslation()(LegacyWelcomeClass);

// Component using the Trans component
/*function MyComponent() {
  return (
    <Trans i18nKey="description.part1">
      To get started, edit <code>src/App.js</code> and save to reload.
    </Trans>
  );
}
*/
// page uses the hook

function App() {
  const { t, i18n } = useTranslation();

  const [language, setLanguage] = useState('en');

  const onSetLanguage = useCallback((lng) => {
    setLanguage(lng);
  }, []);

  const router = createBrowserRouter([
    {
      path: "/",
      element: <div><MainPage/></div>,
    },
    {
      path: "/mainPage",
      element: <div>wowkdjfkdow<MainPage /></div>,
    },
    {
      path: "/A1SubjectPage1",
      element: <div>puripuri<A1SubjectPage1 /></div>,
    },
    {
      path: "/B1ResearcherPage1",
      element: <div>ReRe<B1ResearcherPage1 /></div>,
    },
  ]);

  ReactDOM.createRoot(document.getElementById("root")).render(
    <I18nextProvider i18n={i18n}>
    <React.StrictMode>
      <RouterProvider router={router} />
    </React.StrictMode>
    </I18nextProvider>
  );

  let routes;

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> This is a project
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Hello World Again and Again
        </a>
      </header>
      <Router>
      <div className="App-intro">
       
      </div>
    
        <main>{routes}</main>
      </Router>
    </div>
  );
}

export default App;
import React, { useState, useEffect, Component, Suspense, useCallback} from "react";
import Header from "../Resources/Components/Header";
import Footer from "../Resources/Components/Footer";
import { useTranslation, withTranslation, Trans } from 'react-i18next';
import {MainPageContext, useMainPageContext } from "../Resources/Hooks/mainPageContext";

import "./MainPage.css";

class LegacyWelcomeClass extends Component {
  render() {
    const { t } = this.props;
    return <h2>{t('title')}</h2>;
  }
}
const Welcome = withTranslation()(LegacyWelcomeClass);

const MainPage = () => {
  const { t, i18n } = useTranslation();
  const context = useMainPageContext();
  const [language, setLanguage] = useState('tw');

  const onSetLanguage = useCallback((lng) => {
    setLanguage(lng);
  }, []);

  const [introductionPage, setIntroductionPage] = useState(0);

  const renderLanguageSwitch = () => {
    return [t('testStart'), t('testAgreement')];
  };
  
  const renderButtonSwitch = () => {
    return [t('agree'), t('disagree')];
  };

  return (
    <div className="MainPage">
    <Trans i18nKey="title">
  <h2>{t('title')}</h2>
</Trans>

  
      <Header onSetLanguage={onSetLanguage} />
      <div
        style={{
          width: "100%",
          height: "100vh",
          backgroundColor: "#F5821F",
          margin: "0",
        }}
      >
        {introductionPage === 0 && (
          <button
            className="testStartBox"
            onClick={() => {
              setIntroductionPage(1);
            }}
          >
          {t('agree')}, {t('disagree')}
          </button>
        )}
        {introductionPage !== 0 && (
          <div>
          <div
            className="testDescriptionBox"
            onClick={() => {
              setIntroductionPage(introductionPage + 1);
            }}
          >
           {t('description')}
          </div>
          <div className="testAgreement">

          </div>
          </div>
        )}

        <div
          className="buttonWrapper"
          style={{ display: introductionPage === 1 ? "" : "none" }}
        >
          <button  onClick={() => {
              setIntroductionPage(introductionPage + 1);
            }}> {t('description')}</button>
          <button  onClick={() => {
              setIntroductionPage(0);
            }}>{t('agreement')}</button>
        </div>
      </div>{" "}
      <Footer />

    
    </div>
  );
};
export default MainPage;
import React, { useCallback, useContext } from "react";
import { useMainPageContext } from "../Hooks/mainPageContext";
import { useTranslation } from 'react-i18next';

const Header = () => {
  const { t, i18n } = useTranslation();
  const context = useMainPageContext();
  const { onSetLanguage } = context;

  const toggleLanguage = useCallback((lng) => {
    i18n.changeLanguage(lng);
    onSetLanguage(lng);
  }, [i18n, onSetLanguage]);

  const currentLanguage = i18n.language;

  return (
    <div className="header">
      <h1
        style={{
            display: "flex",
            flexFlow:"row",
            alignItems:"center",


<details>
<summary>英文:</summary>

I have changed the coding , so that it is a context variable passed to the mainPage.js, however, I have another problem, the missing transition key.

Here is my i18n.js

    import i18n from &#39;i18next&#39;;
    import { initReactI18next } from &#39;react-i18next&#39;;
    
    
    
    i18n
      .use(initReactI18next)
      .init({
        backend: {
            loadPath: `/locales/{{lng}}/translation.json`,
            parse: data =&gt; data,
          },
        lng: &#39;en&#39;,
        fallbackLng: &#39;en&#39;,
        debug: true,
        resources: {
          &#39;en&#39;: {
            translation: &#39;en&#39;,
          },
          &#39;tw&#39;: {
            translation: &#39;tw&#39;,
          },
        },
       
        interpolation: {
          escapeValue: false
        }
      });
    
    export default i18n;

Here is the App.js

    import React , { Component, Suspense , useState, useCallback} from &#39;react&#39;;
    import { useTranslation, withTranslation, Trans ,I18nextProvider} from &#39;react-i18next&#39;;
    
    
    import ReactDOM from &quot;react-dom/client&quot;;
    import{
      createBrowserRouter, RouterProvider,BrowserRouter as Router
    } from &quot;react-router-dom&quot;;
    import logo from &#39;./logo.svg&#39;;
    import &#39;./App.css&#39;;
    
    //Import the pages
    import MainPage from &quot;./MainPage/MainPage&quot;;
    import A1SubjectPage1 from &quot;./ASubject/A1SubjectPage1&quot;;
    import B1ResearcherPage1 from &quot;./BResearcher/B1ResearcherPage1&quot;;
    import Header from &#39;./Resources/Components/Header&#39;;
    
    // use hoc for class based components
    
    
    
    class LegacyWelcomeClass extends Component {
      render() {
        const { t } = this.props;
        return &lt;h2&gt;{t(&#39;title&#39;)}&lt;/h2&gt;;
      }
    }
    const Welcome = withTranslation()(LegacyWelcomeClass);
    
    // Component using the Trans component
    /*function MyComponent() {
      return (
        &lt;Trans i18nKey=&quot;description.part1&quot;&gt;
          To get started, edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.
        &lt;/Trans&gt;
      );
    }
    */
    // page uses the hook
    
    
    
    function App() {
    
    
      const { t, i18n } = useTranslation();
    
      const [language, setLanguage] = useState(&#39;en&#39;);
    
      const onSetLanguage = useCallback((lng) =&gt; {
        setLanguage(lng);
      }, []);
    
      const router = createBrowserRouter([
        {
          path: &quot;/&quot;,
          element: &lt;div&gt;&lt;MainPage/&gt;&lt;/div&gt;,
        },
        {
          path: &quot;/mainPage&quot;,
          element: &lt;div&gt;wowkdjfkdow&lt;MainPage /&gt;&lt;/div&gt;,
        },
        {
          path: &quot;/A1SubjectPage1&quot;,
          element: &lt;div&gt;puripuri&lt;A1SubjectPage1 /&gt;&lt;/div&gt;,
        },
        {
          path: &quot;/B1ResearcherPage1&quot;,
          element: &lt;div&gt;ReRe&lt;B1ResearcherPage1 /&gt;&lt;/div&gt;,
        },
      ]);
     
      ReactDOM.createRoot(document.getElementById(&quot;root&quot;)).render(
        &lt;I18nextProvider i18n={i18n}&gt;
        &lt;React.StrictMode&gt;
          &lt;RouterProvider router={router} /&gt;
        &lt;/React.StrictMode&gt;
        &lt;/I18nextProvider&gt;
      );
    
    
    let routes;
    
    
    
    
      return (
        &lt;div className=&quot;App&quot;&gt;
          &lt;header className=&quot;App-header&quot;&gt;
            &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;
            &lt;p&gt;
              Edit &lt;code&gt;src/App.js&lt;/code&gt; This is a project
            &lt;/p&gt;
            &lt;a
              className=&quot;App-link&quot;
              href=&quot;https://reactjs.org&quot;
              target=&quot;_blank&quot;
              rel=&quot;noopener noreferrer&quot;
            &gt;
              Hello World Again and Again
            &lt;/a&gt;
          &lt;/header&gt;
          &lt;Router&gt;
          &lt;div className=&quot;App-intro&quot;&gt;
           
          &lt;/div&gt;
        
            &lt;main&gt;{routes}&lt;/main&gt;
          &lt;/Router&gt;
        &lt;/div&gt;
      );
    }
    
    export default App;

Here is the mainPage.js

    import React, { useState, useEffect, Component , Suspense, useCallback} from &quot;react&quot;;
    import Header from &quot;../Resources/Components/Header&quot;;
    import Footer from &quot;../Resources/Components/Footer&quot;;
    import { useTranslation, withTranslation, Trans } from &#39;react-i18next&#39;;
    import {MainPageContext, useMainPageContext } from &quot;../Resources/Hooks/mainPageContext&quot;;
    
    import &quot;./MainPage.css&quot;;
    
    class LegacyWelcomeClass extends Component {
      render() {
        const { t } = this.props;
        return &lt;h2&gt;{t(&#39;title&#39;)}&lt;/h2&gt;;
      }
    }
    const Welcome = withTranslation()(LegacyWelcomeClass);
    
    const MainPage = () =&gt; {
      const { t, i18n } = useTranslation();
    const context = useMainPageContext();
    const [language, setLanguage] = useState(&#39;tw&#39;);
    
      const onSetLanguage = useCallback((lng) =&gt; {
        setLanguage(lng);
      }, []);
    
    
    
    
    
      const [introductionPage, setIntroductionPage] = useState(0);
    
      //const [language, setLanguage]= useState(0);
    
      //below is the script of the test description. 隨時可以加入新array做新language。
    
      
      const renderLanguageSwitch = () =&gt; {
        return [t(&#39;testStart&#39;), t(&#39;testAgreement&#39;)];
      };
      
      const renderButtonSwitch = () =&gt; {
        return [t(&#39;agree&#39;), t(&#39;disagree&#39;)];
      };
    
      return (
        &lt;div className=&quot;MainPage&quot;&gt;
        &lt;Trans i18nKey=&quot;title&quot;&gt;
      &lt;h2&gt;{t(&#39;title&#39;)}&lt;/h2&gt;
    &lt;/Trans&gt;
    
      
          &lt;Header onSetLanguage={onSetLanguage} /&gt;
          &lt;div
            style={{
              width: &quot;100%&quot;,
              height: &quot;100vh&quot;,
              backgroundColor: &quot;#F5821F&quot;,
              margin: &quot;0&quot;,
            }}
          &gt;
            {introductionPage === 0 &amp;&amp; (
              &lt;button
                className=&quot;testStartBox&quot;
                onClick={() =&gt; {
                  setIntroductionPage(1);
                }}
              &gt;
              {t(&#39;agree&#39;)}, {t(&#39;disagree&#39;)}
              &lt;/button&gt;
            )}
            {introductionPage !== 0 &amp;&amp; (
              &lt;div&gt;
              &lt;div
                className=&quot;testDescriptionBox&quot;
                onClick={() =&gt; {
                  setIntroductionPage(introductionPage + 1);
                }}
              &gt;
               {t(&#39;description&#39;)}
              &lt;/div&gt;
              &lt;div className=&quot;testAgreement&quot;&gt;
    
              &lt;/div&gt;
              &lt;/div&gt;
            )}
    
            &lt;div
              className=&quot;buttonWrapper&quot;
              style={{ display: introductionPage === 1 ? &quot;&quot; : &quot;none&quot; }}
            &gt;
              &lt;button  onClick={() =&gt; {
                  setIntroductionPage(introductionPage + 1);
                }}&gt; {t(&#39;description&#39;)}&lt;/button&gt;
              &lt;button  onClick={() =&gt; {
                  setIntroductionPage(0);
                }}&gt;{t(&#39;agreement&#39;)}&lt;/button&gt;
            &lt;/div&gt;
          &lt;/div&gt;{&quot; &quot;}
          &lt;Footer /&gt;
    
        
        &lt;/div&gt;
      );
    };
    export default MainPage;

Here is the Header.js

    import React, { useCallback, useContext } from &quot;react&quot;;
    import { useMainPageContext } from &quot;../Hooks/mainPageContext&quot;;
    import { useTranslation } from &#39;react-i18next&#39;;
    
    const Header = () =&gt; {
      const { t, i18n } = useTranslation();
      const context = useMainPageContext();
      const { onSetLanguage } = context;
    
      const toggleLanguage = useCallback((lng) =&gt; {
        i18n.changeLanguage(lng);
        onSetLanguage(lng);
      }, [i18n, onSetLanguage]);
    
      const currentLanguage = i18n.language;
    
      return (
        &lt;div className=&quot;header&quot;&gt;
          &lt;h1
            style={{
                display: &quot;flex&quot;,
                flexFlow:&quot;row&quot;,
                alignItems:&quot;center&quot;,
              width: &quot;calc(100% - 10%)&quot;,
              height: &quot;4vh&quot;,
              backgroundColor: &quot;white&quot;,
              paddingTop:&quot;0&quot;,
              padding: &quot;2.5%&quot;,
              paddingLeft: &quot;5%&quot;,
              paddingRight: &quot;5%&quot;,
              justifyContent:&quot;space-between&quot;
            }}
          &gt;
            &lt;div style={{display:&quot;flex&quot;, color: &quot;#F5821F&quot;,}}&gt;
             &lt;img src={require(&quot;../Images/cmghLogo.png&quot;)} style={{width:&quot;50%&quot;, height:&quot;7.5%&quot;, marginTop:&quot;0vh&quot;}} alt=&quot;logo&quot;/&gt;
            &lt;div style={{ top: &quot;0&quot;, margin: &quot;0vh&quot;, marginLeft:&quot;2vw&quot;, width:&quot; 100%&quot;, fontSize:&quot;3vw&quot;}}&gt;中心&lt;/div&gt;    
            &lt;/div&gt;
            &lt;div&gt;
              &lt;header&gt;
                &lt;button onClick={() =&gt; toggleLanguage(&#39;en&#39;)} disabled={currentLanguage === &#39;en&#39;}&gt;English&lt;/button&gt;
                &lt;button onClick={() =&gt; toggleLanguage(&#39;tw&#39;)} disabled={currentLanguage === &#39;tw&#39;}&gt;中文&lt;/button&gt;
              &lt;/header&gt;
            &lt;/div&gt;
          &lt;/h1&gt;
        &lt;/div&gt;
      );
    };
    
    export default Header;



</details>



# 答案2
**得分**: 0

```javascript
// i18n.js没有正确设置。
// 因此无法读取翻译键值对。

// 在我更改为安装并使用"i18next-http-backend"插件后,修改了i18n.js,问题已解决,如下所示:

import i18n from 'i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';

i18n
  // 使用http加载翻译 -> 参见 /public/locales
  // 了解更多:https://github.com/i18next/i18next-http-backend
  .use(Backend)
  // 检测用户语言
  // 了解更多:https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // 将i18n实例传递给react-i18next。
  .use(initReactI18next)
  // 初始化i18next
  // 有关所有选项,请阅读:https://www.i18next.com/overview/configuration-options
  .init({
    fallbackLng: 'en',
    debug: true,

    interpolation: {
      escapeValue: false, // 对于React,不需要此选项,默认会进行转义
    },
  });

export default i18n;
英文:

The i18n.js did not set properly.
so that failed to read the translation key-value pair.

After I changed to install and using "i18next-http-backend" plugin, modified the i18n.js, the problem is fixed as the following:

import i18n from &#39;i18next&#39;;
import Backend from &#39;i18next-http-backend&#39;;
import LanguageDetector from &#39;i18next-browser-languagedetector&#39;;
import { initReactI18next } from &#39;react-i18next&#39;;
i18n
// load translation using http -&gt; see /public/locales
// learn more: https://github.com/i18next/i18next-http-backend
.use(Backend)
// detect user language
// learn more: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// pass the i18n instance to react-i18next.
.use(initReactI18next)
// init i18next
// for all options read: https://www.i18next.com/overview/configuration-options
.init({
fallbackLng: &#39;en&#39;,
debug: true,
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
});
export default i18n;

huangapple
  • 本文由 发表于 2023年2月16日 15:58:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定