Javascript 如何为带有数据数组的React组件传递用于内联样式设置的道具?

Javascript 如何为带有数据数组的React组件传递用于内联样式设置的道具?,javascript,json,reactjs,Javascript,Json,Reactjs,这是我的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 => (

这是我的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;

不要通过
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;
}
功能显示数据(道具){
const DataComponent=SwatchData.map(数据=>(
));
返回数据组件;
}

此外,您还需要使用
backgroundColor
来使用内联样式更改背景色。

只需基于命名颜色提取单个十六进制颜色值即可

const swatchData=[{
id:1,
颜色:“红色”,
十六进制:“E73550”
},
{
id:2,
颜色:“绿色”,
十六进制:“A6A7DC”
}
];
常量道具={
数据:{
颜色:“红色”,
},
};
const getColor=color=>{
const-swatch=swatchData.find(swatch=>swatch.color==color);
返回样本?swatch.hex:“#000”;
}
log(getColor('red'));
log(getColor('green');
log(getColor('royalPurple');

log(getColor(props.data.color))有什么问题吗?你试过什么,有问题吗@Drew-是的,这不起作用……我想更改div dynamically的背景颜色。我遇到了一个错误“无法读取未定义的属性‘颜色’”。我误解了原始问题。看起来你根本没有使用道具。我已经更新了我的答案。但是,由于ShowData已定义但从未使用,因此我收到一个错误,您在应用程序中导入它的位置在哪里?明白了,我只需要导出默认ShowData我是否将SwatchData.js文件更新为这个减去console.log?ShowData组件中仍然存在问题。更新{{backgroundcolor:props.data.color}}时,我出现了一个错误“无法读取未定义的属性'color'”…我是新来的,反应很简单:)@JoshCusick我明白了,我之前完全误解了你的问题。留下它以防以后对其他人有用,并添加了如何将样例数据直接映射到JSX。
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;
}