admin管理员组文章数量:1384149
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
2 Answers
Reset to default 4Passing 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 div
s 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"
}} />
}
本文标签: javascriptreact how to pass props to inline css style in componentsStack Overflow
版权声明:本文标题:javascript - react how to pass props to inline css style in components - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744488211a2608578.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论