【问题标题】:Styling a part of an array in JSX在 JSX 中为数组的一部分设置样式
【发布时间】:2021-01-26 13:24:30
【问题描述】:

我有一个数组,

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>  

【问题讨论】:

  • whats letter aka messages
  • 投票结束,因为问题是由拼写错误引起的。属性名称是 opacity 而不是 Opacity。 JavaScript 区分大小写。
  • 请不要关闭,我改错了

标签: javascript html arrays reactjs web


【解决方案1】:

在设置 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>;

【讨论】:

  • 为此,整个列表都会受到影响,而不仅仅是部分列表受条件影响
  • 对于列表中的其他项目,您只是默认为不透明度 1,而对于年龄 > 5 的项目,您只需设置 0.5。
  • 它成功了,那么我将如何对其进行更多研究,比如进程的名称是什么
【解决方案2】:

为什么不把年龄检查移到 style 属性中呢?

{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>
      );
    })}

另外你在 opacity 属性中有一个错字,你必须用小写写它

【讨论】:

  • 哇,我从来没有想过这个,我会尽力回复你
  • 这实际上是一个错字
  • 但我只需要数组中大于 5 的部分,来赋予不透明度,而不是整个数组
猜你喜欢
  • 2019-10-01
  • 2021-04-01
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 2016-03-05
  • 1970-01-01
相关资源
最近更新 更多