【问题标题】:react how to pass props to inline css style in components反应如何将道具传递给组件中的内联css样式
【发布时间】:2019-11-08 13:02:58
【问题描述】:

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

当前代码不起作用

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

哪一部分出了问题?谢谢。

【问题讨论】:

标签: javascript css reactjs


【解决方案1】:

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

你需要它backgroundColor 来制作“彩色方块”。

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

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

【讨论】:

    【解决方案2】:

    快速浏览一下您的代码,我可以看到您将 color 道具传递给 SketchExample,这是一个带有诸如 rg 等道具的对象。但在 SketchExample 内部 @987654326 @s style.color 是对象,而不是实际颜色。试试这样的:

    render() {
        const { color } = this.props;
    
        return <div style={{ 
            color: `rgba(${color.r},${color.g},${color.b},${color.a})`,
            width: "36px",
            height: "36px" 
        }} />
    }
    

    【讨论】:

      猜你喜欢
      • 2015-11-20
      • 2017-08-17
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 2022-01-03
      • 2020-04-10
      • 1970-01-01
      相关资源
      最近更新 更多