最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react how to pass props to inline css style in components - Stack Overflow

programmeradmin0浏览0评论

I need to draw some colored squares and use props to control the color of these squares.

The current code is not working

   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;

And the app.js file

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

Which part went wrong? Thanks.

I need to draw some colored squares and use props to control the color of these squares.

The current code is not working

   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;

And the app.js file

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

Which part went wrong? Thanks.

Share Improve this question asked Jun 26, 2019 at 14:32 santokusantoku 3,44710 gold badges50 silver badges82 bronze badges 1
  • Possible duplicate of stackoverflow./a/37827390/2427237 – nimsrules Commented Jun 26, 2019 at 14:36
Add a ment  | 

2 Answers 2

Reset to default 4

Passing color will make the text inside the div of that color.

What you need it backgroundColor to make "colored squares".

Also, you can't pass an object to a styles, it need to be a string.

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

From a quick glance of your code I can see you pass a color prop to SketchExample which is an object with props such as r and g and etc. Yet inside SketchExample the divs style.color is the object, not the actual color. Try something like this:

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

    return <div style={{ 
        color: `rgba(${color.r},${color.g},${color.b},${color.a})`,
        width: "36px",
        height: "36px" 
    }} />
}
发布评论

评论列表(0)

  1. 暂无评论