如何使用样式组件对用array.map创建的单个元素进行样式设置?

时间:2020-08-03 17:01:28

标签: javascript css reactjs styled-components

目标是能够针对每个唯一元素,使其具有独特的样式。

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

ec.presence_of_element_located((By.XPATH, locator))

2 个答案:

答案 0 :(得分: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>
  ))
</>

答案 1 :(得分:0)

您可以通过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' />