reactjs - 具有映射数据的动态样式组件
问题描述
我正在尝试提取在 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;
}
`;
我已经减少了代码,所以不要在意未使用的数据。
解决方案
以下是如何使用对象属性进行样式设置:
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
推荐阅读
- java - 如何使用解析制作一个简单的 Twitter 克隆应用程序?
- php - 为 docker docker-compose php-fpm 启用 Soap 客户端
- php - 类似类的类名和文件名的 PSR
- qliksense - qliksense : 在内部网站中嵌入 qlik 仪表板
- typescript - 我如何模拟 angular-auth-oidc 客户端以返回假数据
- mlflow - 运行初始创建后是否可以设置/更改 mlflow 运行名称?
- performance - Ubuntu 18.04 上的 Docker 容器中的进程运行缓慢
- html - 是什么导致我的 HTML 文件不加载我的 CSS?
- svg - SVG 动画标签导致不希望的放回
- python - Python Scrapy 返回不同的 url