[英]How to change background color based on a value with NextJS and TailwindCSS?
I have a table that displays values from my API.我有一个表格,显示来自我的 API 的值。 I am wanting to change the background of the Status Field based on the value received for
request.status
我想根据收到的
request.status
值更改状态字段的背景
I have a total of 4 status values我总共有 4 个状态值
What would be the best way to go about this? go 关于这个问题的最佳方法是什么?
export default function RequestPage() {
const [requests, setRequest] = useState([]);
useEffect(() => {
const fetchRequests = async () => {
const res = await fetch('/api/requests');
const data = await res.json();
console.log(data);
setRequest(data);
};
fetchRequests();
}, [setRequest]);
return (
{requests.map((request) => {
return (
<span aria-hidden="true" className="absolute inset-0 opacity-50 rounded-full bg-green-200"></span>
<span className="relative">{request.status}</span>
)}
})
I am using Typescript.我正在使用 Typescript。 This is the first Typescript project I have done.
这是我做的第一个 Typescript 项目。
You could define a bgColor
variable representing the class for the background color and change it based on the request.status
:您可以定义一个
bgColor
变量,代表 class 作为背景颜色,并根据request.status
更改它:
{
requests.map((request) => {
let bgColor = '';
switch (request.status) {
case 'Completed':
bgColor = 'bg-green-200';
break;
case ...
}
return (
<>
<span
aria-hidden='true'
className={`absolute inset-0 opacity-50 rounded-full ${bgColor}`}
></span>
<span className='relative'>{request.status}</span>
</>
);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.