使用 React Intl 和 Typescript 检查消息是否为空



我有一个使用 React Intl 和 TypeScript 的应用程序。

我想显示一个包含一些信息文本的框,并且我希望仅在文本实际存在时才显示它。

但我做不到

<FormattedMessage id="my.id" />

因为如果my.id没有值,React Intl 将回退到消息 id,即my.id

所以我试图做的是

const myId: string = 'myId';
const info: string = <FormattedMessage id={myId} />;
const infoExists: boolean = myId === info;

但是,infoJSX.Element,而不是string

有没有办法做这样的事情?

对于 JS

const stringExists = !!this.props.intl.messages[id];

正如这里回答的那样

我想通了。

const id: string = 'id';
const componentToBeRenderedIfIdHasValue = ...;
<FormattedMessage id={id}>
{
(message: string) =>
message === id
? null
: componentToBeRenderedIfIdHasValue
}
</FormattedMessage>

我希望这可以对某人有所帮助。

最新更新