反应如何将道具传递给组件中的内联CSS样式

时间:2019-06-26 14:32:17

标签: javascript css reactjs

我需要画一些彩色的正方形,并使用道具来控制这些正方形的颜色。

当前代码无效

   import React from "react"; 

   class SketchExample extends React.Component {

   constructor(props) {
    super(props);   
   }


   render() {
    const { color } = this.props;

    return <div style={{ color: this.props.color, width: "36px", height: "36px" }} />;   } }

   export default SketchExample;

还有app.js文件

import React from "react";
import ReactDOM from "react-dom";
import SketchExample from "./SketchExample";

function App() {
  return (
    <div className="App">
      <SketchExample color={{ r: "201", g: "112", b: "19", a: "1" }} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

哪一部分出错了?谢谢。

2 个答案:

答案 0 :(得分:3)

传递color将使文本位于该颜色的div之内。

backgroundColor可以用来制作“彩色正方形”。

此外,您不能将对象传递给样式,它必须是字符串。

return (
    <div 
        style={{ backgroundColor: `rgba(${Object.values(this.props.color).join(", ")})`, width: "36px", height: "36px" }} 
    /> 
);

答案 1 :(得分:1)

快速浏览一下代码,我可以看到您向color传递了一个SketchExample道具,该对象是带有rg等道具的对象。但是在SketchExample div style.color内部是对象,而不是实际颜色。尝试这样的事情:

render() {
    const { color } = this.props;

    return <div style={{ 
        color: `rgba(${color.r},${color.g},${color.b},${color.a})`,
        width: "36px",
        height: "36px" 
    }} />
}
相关问题