[英]How do I pass a prop for inline styling for React component with an array of data?
Here is my ShowData component that renders in my App.js and then in my index.js这是我的 ShowData 组件,它在我的 App.js 中呈现,然后在我的 index.js 中呈现
import React from "react";
import SwatchData from "./SwatchData";
import { DataTestContainer } from "./DataTestContainer";
function ShowData(props) {
const DataComponent = SwatchData.map(data => (
<DataTestContainer color={data.color} key={data.id} hex={data.hex} />
));
return (
<div style={{ background: "{props.data.color}" }}>{DataComponent}</div>
);
}
export default ShowData;
what I am looking to dynamically change the style of the final div based on the data.color prop我希望根据 data.color 属性动态更改最终 div 的样式
const SwatchData = [
{
id: 1,
color: "red",
hex: "#E73550"
},
{
id: 2,
color: "green",
hex: "#A6A7DC"
}
];
export default SwatchData;
Instead of mapping though SwatchData
and then trying to wrap it separately, do it all together -不要通过
SwatchData
进行映射,然后尝试单独包装它,而是一起完成 -
function ShowData(props) {
const DataComponent = SwatchData.map(data => (
<div style={{ backgroundColor: data.color }}>
<DataTestContainer color={data.color} key={data.id} hex={data.hex} />
</div>
));
return DataComponent;
}
Also, you need to use backgroundColor
to change the background color using inline styles.此外,您需要使用
backgroundColor
使用内联 styles 更改背景颜色。
Just extracting a single hex color value based on a named color只需根据命名颜色提取单个十六进制颜色值
const swatchData = [{ id: 1, color: "red", hex: "#E73550" }, { id: 2, color: "green", hex: "#A6A7DC" } ]; const props = { data: { color: 'red', }, }; const getColor = color => { const swatch = swatchData.find(swatch => swatch.color === color); return swatch? swatch.hex: '#000'; } console.log(getColor('red')); console.log(getColor('green')); console.log(getColor('royalPurple')); console.log(getColor(props.data.color));
[edit] [编辑]
Map the swatch data to JSX directly. Map 将样本数据直接发送到 JSX。 Use the
id
as the key on the outer div so you don't get any react-key warnings, and pass the color
and hex
on to DataTestContainer
.使用
id
作为外部 div 上的键,这样您就不会收到任何 react-key 警告,并将color
和hex
传递给DataTestContainer
。
function ShowData(props) {
return SwatchData.map(({ color, hex, id }) => (
<div key={id} style={{ background: color }}>
<DataTestContainer color={color} hex={hex} />
</div>
));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.