[英]react how to pass props to inline css style in components
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 还有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);
Which part went wrong? 哪一部分出了错? Thanks.
谢谢。
Passing color
will make the text inside the div
of that color. 传递
color
会使文本在该颜色的div
内。
What you need it backgroundColor
to make "colored squares". 您需要的是
backgroundColor
来制作“彩色正方形”。
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. 快速浏览一下代码,我可以看到您将一个
color
道具传递给了SketchExample
,它是一个带有r
和g
等道具的对象。但是在SketchExample
内部, div
的style.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"
}} />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.