繁体   English   中英

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

[英]How to style individual elements created with array.map using styled-components?

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

在我的代码中,有问题的数组是一个对象数组,每个 dummyElement 都将具有基于当前项目键值的唯一绝对 position,例如 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>
  ))
</>

根据官方文档。 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> )) </>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM