在同一文件中使用的react-intl组件的打字稿类型

时间:2019-12-02 15:05:56

标签: javascript reactjs typescript react-intl

我希望在文件中使用injectIntl组件(而不是通常的export default injectIntl(Component)),但是在键入该组件时遇到问题。

我的代码如下:

type IProps = {
  name: string;
}

// I want this to be generate if decide to sent through different props.
type SFCIntl<T> = SFC<WithIntlProps<WrappedComponentProps<any> & T>>;

const Name: SFCIntl<IProps> = injectIntl(({intl, name}) => {
  return (
    <div>{intl.formatMessage({id: name})}</div>
  );
});

const Title: SFC = () => {
  return (<Name name='t.name' />);
}

以上内容将产生错误name does not exist on type 'IntlShape'。要使它正常工作,正确的类型是什么?

1 个答案:

答案 0 :(得分:0)

尽管您具有功能组件,所以我建议您使用useIntl()钩子。 injectIntl用于类组件。

如果您仍然想使用临时选项,则需要对类型使用WrappedComponentProps,例如:

import { injectIntl, WrappedComponentProps } from 'react-intl'

type IProps = {
  name: string;
} & WrappedComponentProps

const Name = injectIntl(({intl, name}:IProps) => {
  return (
    <div>{intl.formatMessage({id: name})}</div>
  );
});

const Title = () => {
  return (<Name name='t.name' />);
}

使用钩子看起来像这样

import { useIntl } from 'react-intl'

type IProps = {
  name: string;
} 

const Name =({ name }:IProps) => {
  const intl = useIntl()
  return (
    <div>{intl.formatMessage({id: name})}</div>
  );
};

const Title = () => {
  return (<Name name='t.name' />);
}