【问题标题】:dynamic styled components with mapped data具有映射数据的动态样式组件
【发布时间】:2020-11-03 12:52:52
【问题描述】:

我正在尝试提取在 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,
  }
]

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

我正在努力了解如何将 items 数据(例如“padding”或“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;
  }
`;

我已经删减了代码,所以不用管那些没用的数据。

【问题讨论】:

    标签: reactjs next.js styled-components


    【解决方案1】:

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

    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
      }
    ];
    

    您可以在此处阅读有关使用组件的props 传递数据以进行样式设置的更多信息:https://styled-components.com/docs/basics#adapting-based-on-props

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 2016-09-11
      • 2021-03-10
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 2019-02-26
      • 2015-01-27
      相关资源
      最近更新 更多