2016-11-24 176 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> 
    ); 
} 

我用InjectedIntlProps類型的國際道具,因爲IntlShape沒有似乎提供了一個FORMATMESSAGE方法。

我增加了一個?到intl道具,因爲我一直有一個「屬性」intl'缺少「(但不injectIntl​​應該返回一個組件沒有這個道具?)

現在它編譯,但運行時出現錯誤(」無法讀取屬性'displayName'的未定義「我猜是因爲默認導出沒有明確的名稱)。

我覺得我不會走向正確的方向,但找不到任何typecript/react-intl項目的例子。

感謝您的幫助!

回答

6

問題是由於打字稿定義的版本。 當使用@類型/反應-國際「:‘^ 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

沒」 t爲我工作......但改變「擴展React.Component」爲「擴展React.PureComponent」。 – karfus

+0

對我來說同樣重要......導出類後,「導出默認值」必須出現! – karfus

+0

我再次編輯它。事實上,您需要將輸出行放在文件末尾,您可以擴展「InjectedIntlProps」而不是手動添加intl道具 – Emarco

1

同樣的問題,我發現包括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); 
0

現有的解決方案都不適用於我。相反,這是由於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);