首页 > 解决方案 > 具有映射数据的动态样式组件

问题描述

我正在尝试提取在 json 中基本上看起来像这样的 JSON 数据:

"items": [
  {
    "id": "1",
    "title": "data header one",
    "bgColor": "dark",
    "buttonColor": "red",
    "shadow": false,
    "offset": 1,
    "padding": 0,
  },
  {
    "id": "2",
    "title": "data header two",
    "bgColor": "light",
    "buttonColor": "black",
    "shadow": false,
    "offset": 1,
    "padding": 0,
  }
]

我正在尝试通过使用将这些数据映射到 next.js 功能组件中map()

我正在努力查看如何将items诸如“填充”或“buttonColor”或“bgColor”之类的数据传递回返回的渲染之外的我的样式组件。有没有办法不使用内联样式?

我的回报是这样设置的:

return (
  <>
  {items.map(({id, title, bgColor, buttonColor, shadow, padding}) => {
    return (
    <Cta key={id}>
      <Div>
      {title}
      </Div>
    </Cta>
    )}}
  </>
);

我的样式组件设置如下:

const Cta = styled.div`
  background: ${bgColor};
  h4 {
  font-weight: bold;
  padding: ${padding}px;
  }
`;

我已经减少了代码,所以不要在意未使用的数据。

标签: reactjsnext.jsstyled-components

解决方案


以下是如何使用对象属性进行样式设置:

import React from "react";
import styled from "styled-components";

export default function App() {
  const Cta = styled.div`
    background: ${props => props.bgColor};
    h4 {
      color: blue;
      font-weight: bold;
      padding: ${props => props.padding}px;
    }
  `;

  const elements = items.map(item => (
    <Cta key={item.id} bgColor={item.buttonColor} padding={item.padding}>
      <h4>Heading</h4>
      {item.title}
    </Cta>
  ));

  return <div className="App">{elements}</div>;
}

const items = [
  {
    id: "1",
    title: "data header one",
    bgColor: "dark",
    buttonColor: "red",
    shadow: false,
    offset: 1,
    padding: 10
  },
  {
    id: "2",
    title: "data header two",
    bgColor: "light",
    buttonColor: "black",
    shadow: false,
    offset: 1,
    padding: 0
  }
];

在这里,您可以阅读有关使用组件传递样式数据的更多信息propshttps ://styled-components.com/docs/basics#adapting-based-on-props


推荐阅读