在JSX中为数组的一部分设置样式



我有一个数组,

const arr = [
{ age: 1, name: 'Raphael' },
{ age: 3, name: 'Inyang' },
{ age: 6, name: 'Ifiok' },
{ age: 8, name: 'Ekpedeme' }
];

我需要年龄在5岁以上才能有0.5的不透明度,而其他人的不透明度将为1

function changeOpacityOfArray(letter) {
if (arr.age >= 5 ) {
letter.style.opacity= '0.5';
}

}
changeOpacityOfArray(arr);

以上内容在JSX、中不起作用

它说不能为未定义的元素设置样式

然后在HTML正文中,注意样式中的不透明度

<ul style={{listStyleType: 'none'}}>
{arr.map(function(item){
return (<li><div style={{display: 'flex', justifyContent: 'flex-start', width: 'auto', fontSize: 'calc(4px + 2vmin)', opacity: 1, justifyContent: 'flex-start' }}><p>{item.name}: {item.age}</p></div></li>)
}
)}
</ul>  

为什么不将年龄检查移到样式道具中?

{arr.map(function (item) {
return (
<li>
<div
style={{
display: "flex",
justifyContent: "flex-start",
width: "auto",
fontSize: "calc(4px + 2vmin)",
opacity: item.age > 5 ? 0.5 : 1,
justifyContent: "flex-start",
}}
>
<p>
{item.name}: {item.age}
</p>
</div>
</li>
);
})}

此外,你在不透明道具中有一个拼写错误,你必须用小写写它

设置div样式时,可以检查item的年龄并相应地设置不透明度。
const arr = [
{ age: 1, name: 'Raphael' },
{ age: 3, name: 'Inyang' },
{ age: 6, name: 'Ifiok' },
{ age: 8, name: 'Ekpedeme' },
];
<ul style={{ listStyleType: 'none' }}>
{arr.map(function (item) {
return (
<li>
<div
style={{
display: 'flex',
justifyContent: 'flex-start',
width: 'auto',
fontSize: 'calc(4px + 2vmin)',
opacity: item.age > 5 ? 0.5 : 1,
justifyContent: 'flex-start',
}}>
<p>
{item.name}: {item.age}
</p>
</div>
</li>
);
})}
</ul>;

最新更新