4

我想用react-intl來做語言翻譯。當我使用這個<FormattedMessage id='importantNews' />時,它工作得很完美。但是,當我使用intl.formatMessage()下面的代碼時,它不起作用並拋出一些錯誤。我不知道它有什麼問題。intl.formatMessage不起作用 - react-intl

import { injectIntl, FormattedMessage } from 'react-intl'; 

function HelloWorld(props) { 
    const { intl } = props; 
    const x = intl.formatMessage('hello') + ' ' + intl.formatMessage('world'); //not working 
    const y = <FormattedMessage id='hello' />; //working 
    return (
    <button>{x}</button> 
); 
} 

export default injectIntl(HelloWorld); 

我的根組件是這樣的,

import ReactDOM from 'react-dom'; 
import { addLocaleData, IntlProvider } from 'react-intl'; 
import enLocaleData from 'react-intl/locale-data/en'; 
import taLocaleData from 'react-intl/locale-data/ta'; 

import HelloWorld from './hello-world'; 

addLocaleData([ 
    ...enLocaleData, 
    ...taLocaleData 
]); 

const messages = { 
    en: { 
    hello: 'Hello', 
    world: 'World' 
    }, 
    ta: { 
    hello: 'வணக்கம்', 
    world: 'உலகம்' 
    } 
}; 

ReactDOM.render(
    <IntlProvider key={'en'} locale={'en'} messages={messages['en']}> 
    <HelloWorld /> 
    </IntlProvider>, 
    document.getElementById('root') 
); 

有人可以幫我解決這個問題?提前致謝。

+0

檢查道具傳遞正確與否。 – Vasi

+0

我希望我正確傳遞道具。你能告訴我你在說什麼道具嗎? –

+0

國際道具。你能解釋你有什麼錯誤嗎? – Vasi

回答

5

你需要調用formatMessageMessageDescriptor,而不僅僅是id

const x = intl.formatMessage({id: 'hello'}) + ' ' + intl.formatMessage({id: 'world'}); 

爲了更好地記住這一點 - 組件被稱爲與道具id

<FormatMessage id="Hello" /> 

道具其實都是鍵值字典:

現在

formatMessage函數接受同樣的道具爲FormatMessage成分:

formatMessage({id: 'hello'}) 
+1

托馬斯,你的解決方案實際上工作。我確實把昨天的代碼放在了其他一些文件中,今天也給我帶來了錯誤。對於那個很抱歉。解釋的答案更清晰。非常感謝!隨着時間的推移,我會刪除我以前的評論 –