使用 React Intl 和 Typescript 检查消息是否为空
Checking if a message is empty with React Intl and 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;
然而,info
是 JSX.Element
,而不是 string
。
有什么办法可以做到这一点吗?
我想通了。
const id: string = 'id';
const componentToBeRenderedIfIdHasValue = ...;
<FormattedMessage id={id}>
{
(message: string) =>
message === id
? null
: componentToBeRenderedIfIdHasValue
}
</FormattedMessage>
希望对大家有所帮助。
对于 JS
const stringExists = !!this.props.intl.messages[id];
如回答here
我有一个使用 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;
然而,info
是 JSX.Element
,而不是 string
。
有什么办法可以做到这一点吗?
我想通了。
const id: string = 'id';
const componentToBeRenderedIfIdHasValue = ...;
<FormattedMessage id={id}>
{
(message: string) =>
message === id
? null
: componentToBeRenderedIfIdHasValue
}
</FormattedMessage>
希望对大家有所帮助。
对于 JS
const stringExists = !!this.props.intl.messages[id];
如回答here