React-intl, use api with Typescript

I would like to use the formatMessage API function to insert a message as a placeholder, but I cannot find the correct way to access this function.

Here is a simplified version of what I have:

//index.tsx
<IntlProvider locale={`fr-FR`} messages={messages_fr}>
    <NameForm/>
</IntlProvider>,

//nameForm.tsx
interface NameFormProps {
   intl?: InjectedIntlProps,
}

export default injectIntl(NameForm);

class NameForm extends React.Component<NameFormProps, {}> {

render() {
    let namePlaceholder = this.props.intl.formatMessage(
        {id: "NAME_PLACEHOLDER",
        defaultMessage: "name"
    });

    return (
        <form>
            <input placeholder={namePlaceholder} type="text"/>
        </form>
    );
}

I used InjectedIntlProps as an intl prop type because IntlShape didn't seem to offer the formatMessage method.

I added? to intl prop, because I continued to have the β€œintl 'missing” property (but shouldn't injection injection return a component without this support?)

Now it compiles, but when I start it I get an error message ("I can not read the" displayName "property from undefined", I think, because the export does not have an explicit name by default).

, , typescript/response-intl.

!

+4
3

typescript. @types/react-intl ":" ^ 2.2.0 " .

() , :

//index.tsx
<IntlProvider locale={`fr-FR`} messages={messages_fr}>
  <NameForm/>
</IntlProvider>,

//nameForm.tsx
interface NameFormProps extends InjectedIntlProps {
  placeholder: string,
}

class NameForm extends React.Component<NameFormProps, {}> {

  render() {
    let namePlaceholder = this.props.intl.formatMessage({
       id: this.props.placeholder,
       defaultMessage: "name"
      });

    return (
      <form>
        <input placeholder={namePlaceholder} type="text"/>
      </form>
    );
}

export default injectIntl(NameForm);
+6

, InjectedIntlProps , , , , . InjectedIntlProps, injectIntl , , JSX, intl. , :

    interface NameFormProps {
        // Include all custom properties here.
    }

    class NameForm extends React.Component<NameFormProps & InjectedIntlProps, {}> {
        // Class body.
    }

    export default injectIntl(NameForm);
+1

. - injectIntl , InjectedIntlProps.

, injectIntl, :

interface NameFormProps {
}

class NameForm extends React.Component<NameFormProps & InjectedIntlProps> {
}

export default injectIntl<NameFormProps>(NameForm);

, :

class NameForm extends React.Component<InjectedIntlProps> {
}

export default injectIntl<{}>(NameForm);
0
source

Source: https://habr.com/ru/post/1661826/


All Articles