我有一个 LanguageWrapper 组件直接取自 react-intl 文档示例
//LanguageWrapper.jsx
import React, {useState} from 'react';
import {IntlProvider} from 'react-intl';
import French from '../lang/fr.json'
import Arabic from '../lang/ar.json';
import English from '../lang/en.json';
export const LanguageContext = React.createContext();
const local = navigator.language;
let lang;
if (local === 'en') {
lang = English;
}else {
if (local === 'fr') {
lang = French;
} else {
lang = Arabic;
}
}
const LanguageWrapper = (props) => {
const [locale, setLocale] = useState(local);
const [messages, setMessages] = useState(lang);
function selectLanguage(e) {
const newLocale = e.target.value;
setLocale(newLocale);
if (newLocale === 'en') {
setMessages(English);
} else {
if (newLocale === 'fr'){
setMessages(French);
} else {
setMessages(Arabic);
}
}
}
return (
<LanguageContext.Provider value = {{locale, selectLanguage}}>
<IntlProvider messages={messages} locale={locale}>
{props.children}
</IntlProvider>
</LanguageContext.Provider>
);
}
export default LanguageWrapper;
使用基本的 App.jsx(仅为上下文添加)
//App.jsx
import React, {useContext} from 'react';
import Header from "./components/Header";
import Footer from "./components/Footer";
import { Switch, Route } from 'react-router'
import './App.css';
import ContentArea from "./components/ContentArea";
import {FormattedMessage} from 'react-intl';
import {LanguageContext} from './components/LanguageWrapper'
function App() {
const localeCode = navigator.language;
const languageContext = useContext(LanguageContext)
return (
<div data-testid='app-wrapper' className="App">
<div className="App-header">
<Switch>
<Route>
<Header/>
<ContentArea/>
<select value = {languageContext.locale} onChange={languageContext.selectLanguage}>
<option value= 'en'>English</option>
<option value= 'fr'>French</option>
<option value= 'ar'>Arabic</option>
</select>
<p>
<FormattedMessage
id = "app.header"
defaultMessage="Testing in en-US"
values = {{language: localeCode, code: (word)=> <code>{word}</code>}}
/>
</p>
<Footer/>
</Route>
</Switch>
</div>
</div>
);
}
export default App;
和一个基本的 index.jsx(仅为上下文添加)
//index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
import './index.css';
import LanguageWrapper from './components/LanguageWrapper'
ReactDOM.render(
<LanguageWrapper>
<App/>
</LanguageWrapper>
document.getElementById('root'),
);
// Hot Module Replacement (HMR) - Remove this snippet to remove HMR.
// Learn more: https://www.snowpack.dev/concepts/hot-module-replacement
if (import.meta.hot) {
import.meta.hot.accept();
}
现在这里的问题是我有:
test-ui:
l->src
l-> components
l-> LanguageWrapper.jsx
l-> lang
l-> ar.json
l-> en.json
l-> fr.json
l->index.js
但是当我运行 npm run build 我得到:
UnhandledPromiseRejectionWarning: Error: Can't resolve '../lang/fr.json' in '/Users/me/workSpace/apps/testWebApp/test-ui/build/dist'
我完全不知道我做错了什么,但我觉得它很小......有人可以帮助我吗?