【发布时间】:2021-05-31 04:32:45
【问题描述】:
在我当前的 React 项目中,我需要能够将背景样式(图像、宽度、高度等)从 'div' 更改为九种不同的选项。
我已经用下面的代码试过了:
const styleOptions = [
{
backgroundImage: "",
backgroundRepeat: "no-repeat",
backgroundPosition: "center",
//backgroundSize: "650px 800px",
backgroundSize: "cover"
},
{
backgroundImage: "url(/PicturesPattern/Picture1.png)",
backgroundRepeat: "no-repeat",
backgroundPosition: "center",
//backgroundSize: "650px 800px",
backgroundSize: "cover"
},
...//same code for nine Pictures, only diffrent size values
]
class Example extends React.Component {
state = {
...
...
//for selectionField
isDisabled: false,
backgroundStyle: styleOptions[0]
};
...
...
...
onSelectChange = (event) => {
this.setState({
...
currentStyle: styleOptions[event.value + 1]
});
};
render() {
return (
<>
//div for selectionField
<div className="forBackground" style{this.backgroundStyle}>
...
...
//other code
...
...
</>
)
}
}
但是在我的选择字段发生任何变化时,特定 div 的背景不会发生任何变化。 当我为每个可能的索引添加“styleOptions [x]”时,我得到了特定的背景图像和其他样式选项。
我做错了什么? 希望有人可以帮助我:)
【问题讨论】:
标签: javascript reactjs typescript inline-styles