javascript - 如何在前端使角色有条件?
问题描述
在客户端,我有以下行:
<img data-tip={`${data.name}, ${data.function || ''}`} alt="img" src={data.avatar} />
但是如果函数有值,我只想显示名称和函数之间的逗号。我怎样才能做到这一点?
解决方案
这与 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
属性:要么填写真实的描述,要么不填写。填写一个无意义的值是你能做的最糟糕的事情:屏幕阅读器会为有视觉障碍的人大声读出该属性。
推荐阅读
- sql - 将列更新为虚拟列 oracle
- postgresql - Micronaut:使用 Flyway 在 micronaut-postgres-reactive 上运行数据库迁移(基于 reactive-pg-client)
- vba - MS Word 2016:使用 VBA 删除所有受保护的评论
- mysql - MySQL将时间转换为字符串(Grafana)
- python - 在桌面应用程序中正确集成 wsgiref.simple_server 和 Flask
- java - 如何在两个相同大小的集合中进行操作
- python - PYTHON:每个 x 值的多个 y 值的最佳拟合线
- sql - Microsoft Access:为每个公司选择一个电子邮件地址
- directions - Azure Maps Directions Service 对自行车的错误请求
- javascript - 从 URL 保存 HTML 数据