Ján*_*ťka 2 css reactjs react-router
我已经成功地在 React 中创建了类,并希望将随机生成的背景设置为 div 容器。名为 divStyle 的常量变量确实包含 CSS 函数 rbg() 但我找不到将变量从 this.state 传递到该函数的解决方案
import React from 'react';
import './ShopItem.css';
class ShopItem extends React.Component{
constructor(props){
super(props);
this.state = {
r:Math.floor(Math.random() * 256),
g:Math.floor(Math.random() * 256),
b:Math.floor(Math.random() * 256)
}
}
componentDidMount() {
console.log(this.state.r, this.state.g, this.state.b);
}
render(){
const divStyle = {
background: "rgb()"
};
return(
<div className="Item" style={divStyle} >
{console.log("test")}
{this.props.data}
</div>
);
};
};
export default ShopItem;
Run Code Online (Sandbox Code Playgroud)
您可以使用 es6 反引号并添加使用以下代码,this
引用当前实例,因此this.state
在方法内部可用。
const divStyle = {
background: `rgb(${this.state.r},${this.state.g},${this.state.b})`
};
Run Code Online (Sandbox Code Playgroud)
您可以简单地将它们添加到字符串中:
const divStyle = {
background: "rgb(" + this.state.r + "," + this.state.g + "," + this.state.b + ")"
};
Run Code Online (Sandbox Code Playgroud)