【问题标题】:How do I pass a prop for inline styling for React component with an array of data?如何为带有数据数组的 React 组件传递内联样式的道具?
【发布时间】:2020-04-03 00:44:47
【问题描述】:

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

我希望根据 data.color 属性动态更改最终 div 的样式

const SwatchData = [
  {
    id: 1,
    color: "red",
    hex: "#E73550"
  },
  {
    id: 2,
    color: "green",
    hex: "#A6A7DC"
  }
];

export default SwatchData;

【问题讨论】:

  • 那里有问题吗?你试过什么,有问题吗? How to Ask
  • @Drew - 是的,这不起作用.....我想动态更改 div 的背景颜色

标签: javascript json reactjs


【解决方案1】:

不要通过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;
}

另外,您需要使用backgroundColor 使用内联样式更改背景颜色。

【讨论】:

  • 我收到“无法读取未定义的属性‘颜色’”的错误
  • 我误解了原来的问题。看起来你根本没有真正使用道具。我已经更新了我的答案。
  • 这是有效的,但是因为 ShowData 已定义但从未使用过,所以我收到错误
  • 你在你的应用程序的哪里导入它?
  • 知道了,我只需要export default ShowData;
【解决方案2】:

仅根据命名颜色提取单个十六进制颜色值

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));

[编辑]

将样本数据直接映射到 JSX。使用 id 作为外部 div 上的键,这样您就不会收到任何 react-key 警告,并将 colorhex 传递给 DataTestContainer

function ShowData(props) {
  return SwatchData.map(({ color, hex, id }) => (
    <div key={id} style={{ background: color }}>
      <DataTestContainer color={color} hex={hex} />
    </div>
  ));
}

【讨论】:

  • 我是否将我的 SwatchData.js 文件更新为此减去 console.log?我仍然在 ShowData 组件中遇到问题。更新 {{ backgrounColor : props.data.color }} 时,我收到“无法读取未定义的属性'颜色'”的错误...我是新来的,反应轻松:)
  • @JoshCusick 我明白了,我之前完全误读了你的问题。留下它以防以后对其他人有用,并添加了如何将您的样本数据直接映射到 JSX。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
  • 2019-11-11
  • 2018-06-16
  • 2018-08-01
  • 2020-06-06
  • 1970-01-01
相关资源
最近更新 更多