React-Intl如何在输入占位符中使用FormattedMessage

时间:2016-09-22 05:00:31

标签: reactjs react-intl react-starter-kit

我不确定如何从

获取值
<FormattedMessage {...messages.placeholderIntlText} />

转换为占位符格式,如输入:

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

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

10 个答案:

答案 0 :(得分:73)

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

相反,react-intl提供lower level API的原因完全相同。渲染组件本身在引擎盖下使用此API将值格式化为HTML。您的方案可能要求您使用较低级别的formatMessage(...) API。

您应该使用intl HOC将injectIntl对象注入到组件中,然后通过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功能,因此请根据您的设置进行调整。

答案 1 :(得分:6)

用于输入占位符以获取更多details

int total, i, *numere, negativeSum = 0, positiveSum = 0;

printf("The number of digits you want to calculate the arithmetic amount: : ");
scanf("%d",&total);

numere = malloc(sizeof(int) * total);

for(i=0; i<total; i++){
    printf("Enter number %d : ",(i+1));
    scanf("%d",&numere[i]);
}

for(i=0; i<total ; i++){
   if(numere[i] < 0){
     negativeSum += numere[i];
            }else{
     positiveSum += numere[i];
   }
}

答案 2 :(得分:1)

您正在尝试将名为FormattedMessage的React组件呈现为期望字符串的占位符标记。

您应该只创建一个名为FormattedMessage的函数,该函数将一个字符串返回到占位符。

function FormattedMessage(props) {
    ...
}

<input placeholder=`{$(FormattedMessage({...messages.placeholderIntlText})}` />

答案 3 :(得分:1)

基于react intl wiki,带有可翻译占位符的输入框的实现将如下所示:

import React from 'react';
import { injectIntl, intlShape, defineMessages } from 'react-intl';

const messages = defineMessages({
  placeholder: {
    id: 'myPlaceholderText',
    defaultMessage: '{text} and static text',
  },
});

const ComponentWithInput = ({ intl, placeholderText }) => {
  return (
    <input
      placeholder={ intl.formatMessage(messages.placeholder, { text: placeholderText }) }
    />
  );
};

ComponentWithInput.propTypes = {
  intl: intlShape.isRequired
};

export default injectIntl(ComponentWithInput);

及其用途:

import ComponentWithInput from './component-with-input';
...
render() {
  <ComponentWithInput placeholderText="foo" />
}
...

id: 'myPlaceholderText',部分是必要的,以便babel-plugin-react-intl收集要翻译的邮件。

答案 4 :(得分:0)

在我的情况下,我将整个应用程序放在一个文件中,因此使用export将无法正常工作。这个使用普通的类结构,因此您可以根据需要使用React的状态和其他功能。

class nameInputOrig extends React.Component {
  render () {
    const {formatMessage} = this.props.intl;
    return (
        <input type="text" placeholder={formatMessage({id:"placeholderIntlText"})} />
    );
  }
}

const nameInput = injectIntl(nameInputOrig);

使用创建的常量进行应用:

class App extends React.Component {
    render () {
        <nameInput />
    }
}

答案 5 :(得分:0)

这是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;

然后您可以进行自定义挂钩,以使用API​​提供的方法:

import { useIntl } from 'react-intl'

export function useFormatMessage(messageId) {
  return useIntl().formatMessage({ id: messageId })
}

答案 6 :(得分:0)

从@gazdagerg的答案开始,我调整了他的代码,以便:

  • 具有一个新组件,该组件是 input
  • 的包装
  • 从语言环境conf接收字符串的ID
  • 基于ID,它会返回有关全局语言环境设置的字符串
  • 处理未设置字符串ID的情况(这会导致异常和页面崩溃)

    import React from 'react';
    import { injectIntl, intlShape, defineMessages } from 'react-intl';


    const InputWithPlaceholder = ({ intl, placeholder }) => {

      const messages = defineMessages({
        placeholder: {
          id: placeholder,
          defaultMessage: '',
        },
      });

      if(messages.placeholder.id) {
        return (
          <input placeholder={ intl.formatMessage(messages.placeholder) } />
        );
      } else {
        return (
          <input/>
        );
      }
    };

    InputWithPlaceholder.propTypes = {
      intl: intlShape.isRequired
    };

    export default injectIntl(InputWithPlaceholder);

您可以通过以下方式在其他文件中使用它:

  1. 导入新组件
  2. 以区域设置字符串的ID作为参数使用它
import InputWithIntlPlaceholder from 'your/path/to/component/InputWithIntlPlaceholder';

... more code here ...

<InputWithIntlPlaceholder placeholder="your.locale.string.id" />

答案 7 :(得分:0)

从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.Home': 'placeholder en fançais',
      }
    }
    return ( 
      <IntlProvider locale = {lang} messages = { messages[lang] } >
          <input placeholder = { intl.formatMessage({ id: 'placeholderMessageId' })}/> 
      </IntlProvider >
      );
    };

export default FunctionComponent;

答案 8 :(得分:0)

考虑这种可能性。

最简单的解决方案

<IntlMessages id="category.name">
    {text => (
        <Input placeholder={text} />
    )}
</IntlMessages>

OR

enter image description here

答案 9 :(得分:-1)

像这样:

import React, {PropTypes} from 'react';
import { injectIntl, FormattedMessage } from 'react-intl';
 
/**
* {
* "hello": "Hello",
* "world": "World"
* }
*/
 
// pure function
const PureFunciton = injectIntl(({ intl }) => {
return (
  <div>
    <p>{intl.formatMessage({ id: 'hello' })}</p>
    <p><FormattedMessage id="world" /></p>
  </div>
)
});
 
// class Component
class componentName extends Component {
  handleStr = () => {
    // return 'Hello';
    const { intl } = this.props;
    return intl.formatMessage({ id: 'hello' })
  }
  render() {
    return (
      <div>
        <p>{this.handleStr()}</p>
        <p><FormattedMessage id="world" /></p>
      </div>
    );
  }
}
 
export default injectIntl(connect(componentName));
相关问题