Bry*_*yan 46 reactjs react-intl react-starter-kit
我不确定如何从中获取值
<FormattedMessage {...messages.placeholderIntlText} />
Run Code Online (Sandbox Code Playgroud)
像输入一样占位符格式:
<input placeholder={<FormattedMessage {...messages.placeholderIntlText} />} />
Run Code Online (Sandbox Code Playgroud)
因为它会在实际占位符中返回[Object object].有没有办法获得实际的正确值?
lso*_*ira 90
将<Formatted... />在反应的组分react-intl是为了渲染场景中使用,并不意味着占位符,替换文本等,它们呈现HTML,而不是纯文本,这是不是在你的情况下非常有用使用.
相反,出于同样的原因react-intl提供较低级别的API.渲染组件本身在引擎盖下使用此API将值格式化为HTML.您的方案可能要求您使用较低级别的formatMessage(...)API.
您应该intl使用injectIntlHOC 将对象注入组件,然后通过API格式化消息.
例:
import React from 'react';
import { injectIntl, intlShape } from 'react-intl';
const ChildComponent = ({ intl }) => {
const placeholder = intl.formatMessage({id: 'messageId'});
return(
<input placeholder={placeholder} />
);
}
ChildComponent.propTypes = {
intl: intlShape.isRequired
}
export default injectIntl(ChildComponent);
Run Code Online (Sandbox Code Playgroud)
请注意,我在这里使用了一些ES6功能,因此请根据您的设置进行调整.
lan*_*vel 24
intl道具injectIntlintl
Fin*_*rod 16
现在是 2019 年 7 月,react-intl 3 beta 附带了一个useIntl钩子,以使这些类型的翻译更容易:
import React from 'react';
import {useIntl, FormattedDate} from 'react-intl';
const FunctionComponent: React.FC<{date: number | Date}> = ({date}) => {
const intl = useIntl();
return (
<span title={intl.formatDate(date)}>
<FormattedDate value={date} />
</span>
);
};
export default FunctionComponent;
Run Code Online (Sandbox Code Playgroud)
然后你可以制作自定义钩子来使用 API 提供的方法:
import { useIntl } from 'react-intl'
export function useFormatMessage(messageId) {
return useIntl().formatMessage({ id: messageId })
}
Run Code Online (Sandbox Code Playgroud)
有关输入占位符的更多详细信息
<FormattedMessage id="yourid" defaultMessage="search">
{placeholder=>
<Input placeholder={placeholder}/>
}
</FormattedMessage>
Run Code Online (Sandbox Code Playgroud)
从 React 版本 >= 16.8 开始,您可以使用useIntl hook:
import React from 'react';
import { IntlProvider, useIntl } from 'react-intl';
const FunctionComponent = () => {
const intl = useIntl();
const lang = "en";
const messages = {
en: {
'placeholderMessageId': 'placeholder in english',
},
fr: {
'placeholderMessageId': 'placeholder en fançais',
}
}
return (
<IntlProvider locale = {lang} messages = { messages[lang] } >
<input placeholder = { intl.formatMessage({ id: 'placeholderMessageId' })}/>
</IntlProvider >
);
};
export default FunctionComponent;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37646 次 |
| 最近记录: |