首页 > 解决方案 > 如何在前端使角色有条件?

问题描述

在客户端,我有以下行:

<img data-tip={`${data.name}, ${data.function || ''}`} alt="img" src={data.avatar} />

但是如果函数有值,我只想显示名称和函数之间的逗号。我怎样才能做到这一点?

标签: javascript

解决方案


这与 React 无关,实际上,您是在询问如何在 JS 中编写字符串。

如果逗号(可能是随后的空格)只需要在存在时data.function存在,请使用三元运算符

// template strings allow template strings inside of them:
const tipText = `${data.name}${data.function ? `, ${data.function}` : ``}`;
const description = `some description of what is in this image, or what it illustrates`;
const img = <img data-tip={tipText} alt={description} src={data.avatar} />

或者,没有嵌套字符串:

const suffix = data.function ? `, ${data.function}` : ``;
const tipText = `${data.name}${suffix}`;
const description = `some description of what is in this image, or what it illustrates`;
const img = <img data-tip={tipText} alt={description} src={data.avatar} />

注意alt属性:要么填写真实的描述,要么不填写。填写一个无意义的值是你能做的最糟糕的事情:屏幕阅读器会为有视觉障碍的人大声读出该属性。


推荐阅读