将 react-intl 与 react-bootstrap 一起使用

Using react-intl with react-bootstrap

我有一个模板化的 TextAreaField,它使用 react-bootstrap 中的 FormControl 来赋予它漂亮的 bootstrap 外观和感觉。

我希望能够通过 react-intl 使用国际化消息。它适用于 FormControl 之外的所有组件,但不适用于道具。当我尝试将 FormattedMessage 传递给 placeholder 时,它只显示 [object Object]

有什么想法吗?

TextAreaField.js

import React, {PropTypes} from 'react';
import Help from './Help';
import {FormGroup, ControlLabel, FormControl } from 'react-bootstrap';

const TextAreaField = ({ input, label, tooltip, rows, meta }) => {
    const { touched, warning, error} = meta;
    let currentState = null;
    if (touched) currentState = (error ? "error" : warning ? "warning" : null);
    return (
        <FormGroup controlId={input.name} validationState={currentState}>
            {tooltip && <Help input={input.name} text={tooltip}/>}
            <FormControl
                componentClass="textarea"
                style={{height: rows * 2 + "em"}}
                placeholder={label}
                {...input}
            />
            {currentState && <ControlLabel className={currentState}>{error || warning}</ControlLabel>}
        </FormGroup>
    );
};

TextAreaField.propTypes = {
    input: PropTypes.object.isRequired,
    label: PropTypes.object.isRequired,
    tooltip: PropTypes.object,
    meta: PropTypes.object,
    rows: PropTypes.number,
};

TextAreaField.defaultProps = {
    rows: 3
};

export default TextAreaField;

使用 TextAreaField 的 redux-form

<Field name="text" label={<FormattedMessage id="Order.Text" />} validate={required}
             warn={bigJob} component={TextAreaField} rows={5}/>

占位符需要一个字符串,而不是一个对象。所以你不能使用 FormattedMessage 组件。幸运的是,您可以直接从上下文中访问 react-intl.formatMessage 函数。

例如,这是一个简单的组件,它使用 formatMessage 从上下文到 return 一个包含 label 消息的跨度。

import {Component, createElement, isValidElement} from 'react';
import {intlShape} from '../types';

export default class FormattedMessage extends Component {

    static contextTypes = {
        intl: intlShape,
    };

    render() {
        const {formatMessage, textComponent: Text} = this.context.intl;
        return <span>{formatMessage({id: 'label'})}</span>
    }
}

您可以查找 implementation of the FormattedMessage 组件以获得更复杂的示例。

如果您不想处理上下文而是在需要时注入存储,您也可以考虑使用 react-intl-redux for redux or mobx-react-intl 等库。