React-Intl如何在输入占位符中使用FormattedMessage [英] React-Intl How to use FormattedMessage in input placeholder

查看:1577
本文介绍了React-Intl如何在输入占位符中使用FormattedMessage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何从

<FormattedMessage {...messages.placeholderIntlText} />

转换成类似输入的占位符格式:

into a placeholder format like input:

<input placeholder={<FormattedMessage {...messages.placeholderIntlText} />} />

,因为它将在实际占位符中返回[Object object].有没有办法获得实际的正确值?

as it would return [Object object] in the actual placeholder. Is there a way to get the actual correct value?

推荐答案

react-intl中的<Formatted... /> React组件用于渲染场景,而不用于占位符,替代文本等.它们呈现HTML,而不是纯文本,这在您的方案中没有用.

The <Formatted... /> React components in react-intl are meant to be used in rendering scenarios and are not meant to be used in placeholders, alternate text, etc. They render HTML, not plain text, which is not useful in your scenario.

相反,react-intl为此提供了较低级别的API 原因.呈现组件本身在幕后使用此API将值格式化为HTML.您的方案可能要求您使用较低级别的formatMessage(...) API.

Instead, react-intl provides a lower level API for exactly this same reason. The rendering components themselves use this API under the hoods to format the values into HTML. Your scenario probably requires you to use the lower level formatMessage(...) API.

您应该使用injectIntl HOC将intl对象注入到组件中,然后通过API格式化消息.

You should inject the intl object into your component by using the injectIntl HOC and then just format the message through the 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);

请注意,我在这里使用了一些ES6功能,因此请根据您的设置进行调整.

Please note that I'm using some ES6 features here, so adapt according to your setup.

这篇关于React-Intl如何在输入占位符中使用FormattedMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆