简体   繁体   中英

Using react-intl with react-bootstrap

I've got a templated TextAreaField that uses FormControl from react-bootstrap to give it the nice bootstrap look and feel.

I'm wanting to be able to use internationalised messages via react-intl . It works for all the components outside the FormControl , but not in the props. When I try and pass a FormattedMessage to the placeholder it just displays [object Object]

Any ideas?

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;

The redux-form that uses the TextAreaField

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

The placeholder expects a string, not an object. So you can't use the FormattedMessage component. Fortunately, you can directly access the react-intl.formatMessage function from the context.

For example, here is a simple component that uses formatMessage from the context to return a span containing the label message .

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>
    }
}

You can look up the implementation of the FormattedMessage component for a more complex example.

Also you could consider using a library such as react-intl-redux for redux or mobx-react-intl if you prefer not to deal with the context but inject the stores when needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM