如何使用 hook useIntl 定义 defaultprops

how to define defaultprops using hook useIntl

最近我开始使用 hook useIntl,之前我使用的是 HOC injectIntl。现在我遇到了一个找不到解决方案的问题,如何将 defaultProps 国际化?

类似于:

function Component(props) {
    const intl = useIntl();
    const {name} = props;

    return (
      <div>
         {intl.formatMessage({id: 'welcome'}, {user: name})}
      <div/>
    );
}

Component.defaultProps = {
   name: 'unknown'; <<---------- how to replace this plain string with intl...?
}

Component.propTypes = {
   name: PropType.string
}

export default Component;

看起来没有办法做到这一点,这是我找到的解决方案:

function Component(props) {
    const intl = useIntl();
    let {name} = props;

    if (!name) {
      name = intl.formatMessage({id: 'unknownKey'});
    }

    return (
      <div>
         {intl.formatMessage({id: 'welcome'}, {user: name})}
      <div/>
    );
}

Component.defaultProps = {
   name: null
}

Component.propTypes = {
   name: PropType.string
}

export default Component;

您可以使用 FormattedMessage:

import { FormattedMessage, useIntl } from 'react-intl';

function Component(props) {
    const intl = useIntl();
    const {name} = props;

    return (
      <div>
         {intl.formatMessage({id: 'welcome'}, {user: name})}
      <div/>
    );
}

Component.defaultProps = {
   name: <FormattedMessage id="unknownKey" />
}

Component.propTypes = {
   name: PropType.string
}

export default Component;