【问题标题】:How to style individual elements created with array.map using styled-components?如何使用 styled-components 为使用 array.map 创建的单个元素设置样式?
【发布时间】:2020-11-23 18:40:44
【问题描述】:

目标是能够定位每个独特的元素,以赋予其独特的样式。

在我的代码中,有问题的数组是一个对象数组,每个 dummyElement 将具有基于当前项键值的唯一绝对位置,例如 curr.longitude。

// dummyElement.styled.js file

export const dummyElement = styled.a`
  font-size: 20px;
`; // Styles all the dummyElements, how to style them individually?



// dummyElement.JSX file 

import { dummyElement } from "./dummyElement.styled";

<>
  props.dummyArray.map((current, index) => (
    <dummyElement
      key={index}
      href={"https://dummywebsite/" + current.value}
    >
      {current.value}
    </dummyElement>
  ))
</>

【问题讨论】:

    标签: javascript css reactjs styled-components


    【解决方案1】:

    根据官方文档。 https://styled-components.com/ 我认为解决方案是这样的。试试看,告诉我它是否有效。

    / dummyElement.styled.js file
    
    export const dummyElement = styled.a`
      font-size: 20px;
      ${ props => props.longValue === 'someLongitudeValue' && css`
        background-color: white;
      `}
      ${ props => props.longValue === 'otherLongitudeValue' && css`
        background-color: green;
      `}
    `; // Styles all the dummyElements, how to style them individually?
    
    
    
    // dummyElement.JSX file 
    
    import { dummyElement } from "./dummyElement.styled";
    
    <>
      props.dummyArray.map((current, index) => (
        <dummyElement
          key={index}
          href={"https://dummywebsite/" + current.value}
          longValue={current.long}
        >
          {current.value}
        </dummyElement>
      ))
    </>

    【讨论】:

      【解决方案2】:

      您可以通过id 属性传递动态样式的值,然后在dummyElement 样式组件中解析它们,如下所示:

      // Define your dynamic styled components something like this
      export const DummyElement = styled.div`
        font-size: 20px;
        padding: ${props => Number(props.id.split('-')[2])}px;
        background-color: ${props => props.id.split('-')[1]};
        color: #FBE7FD;
      `;
      
      // Then when using the DummyComponent do something like this
      <DummyElement id='dummy1-coral-100' />
      <DummyElement id='dummy2-indianred-50' />
      <DummyElement id='dummy3-pink-20' />
      

      【讨论】:

        猜你喜欢
        • 2020-08-18
        • 2020-04-04
        • 1970-01-01
        • 2021-08-16
        • 2019-07-15
        • 2019-12-21
        • 2019-12-21
        • 2020-09-21
        • 2021-12-06
        相关资源
        最近更新 更多