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

托马斯,你的解决方案实际上工作。我确实把昨天的代码放在了其他一些文件中,今天也给我带来了错误。对于那个很抱歉。解释的答案更清晰。非常感谢!随着时间的推移,我会删除我以前的评论 –