2016-11-24 21 views
4

react-intl APIのformatMessage関数を使用してプレースホルダとしてメッセージを挿入したいが、この関数にアクセスする正しい方法を理解できない。ここでReact-intl、TypescriptでAPIを使用する

は、私が持っているものの簡易版である:

//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> 
    ); 
} 

IntlShapeがFORMATMESSAGE方法を提供しているようだしなかったので、私は、国際小道具の種類としてInjectedIntlPropsを使用しました。

私は?私は "Property 'intl'が存在しないためにintl propを使用していました。(しかし、このpropを持たないコンポーネントを返すのはinjectIntl​​ではありません)

これはコンパイルされますが、未定義のプロパティ 'displayName'を読み取ることはできません "デフォルトのエクスポートには明示的な名前がないので推測します。

私は正しい方向に行かないと思っていますが、typescript/react-intlプロジェクトの例は見つかりません。

ありがとうございました!

答えて

6

この問題は、typescript定義のバージョンに起因しています。 種類@使用する場合/・インターナショナルの反応 ":『^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); 
+0

のdidn:何の小道具がない場合

interface NameFormProps { } class NameForm extends React.Component<NameFormProps & InjectedIntlProps> { } export default injectIntl<NameFormProps>(NameForm); 

、それは若干変更する必要があります

それを修正するために、私は明示的に何が包まれたコンポーネントが持つべき小道具injectIntlを教えていました私のために働く...しかし、 "React.Component"を "React.PureComponentを拡張する"に変更しました。 – karfus

+0

また、私にとって重要なのは...「輸出のデフォルト」は輸出されたクラスの後に来なければなりません! – karfus

+0

私は再びそれを編集しました。実際には、ファイルの最後にエクスポート行を置く必要があり、手動でintl小道具を追加する代わりに "InjectedIntlProps"を拡張することができます – Emarco

1

をして作業中同じ問題ですが、質問に記載されているように、InjectedIntlPropsをメンバーとして含めることも、別の答えに記載されているようにそれを拡張することも、タイプチェッカーを満たしていないことが判明しました。InjectedIntlProps、 JSXのコンポーネントはintlプロパティを提供すると考えていましたが、次の戦略で解決しました:

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

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

    export default injectIntl(NameForm); 
0

いずれの既存の解決策も私には役に立たなかった。その代わりに、InjectedIntlPropsを含むようにプロパティを推測するのはinjectIntlであった。 「

class NameForm extends React.Component<InjectedIntlProps> { 
} 

export default injectIntl<{}>(NameForm); 
関連する問題