如何使用选择框更改 div 的背景样式?
How can I change background-style of div with a selection box?
在我当前的 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 的背景没有任何变化。
当我为 x 每个可能的索引放置“styleOptions[x]”时,我得到特定的背景图像和其他样式选项。
我做错了什么?
希望有人能帮助我:)
那么,在 onSelectChange
函数和 event.value + 1
部分中,您将添加两种不同类型的变量(字符串和整数)。因此,div 的背景样式将无法正确更改。首先,你应该像下面这样写这个函数
onSelectChange = (event) => {
this.setState({
backgroundStyle: styleOptions[parseInt(event.target.value) + 1],
});
};
那么,style{this.backgroundStyle}
应该改为style={this.state.backgroundStyle}
。我还添加了高度属性并分配了一个 backgroundColor
以使 div 和更改更明显
但也有其他小的修改。因此,请检查代码更正版本的 sandbox。
在我当前的 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 的背景没有任何变化。 当我为 x 每个可能的索引放置“styleOptions[x]”时,我得到特定的背景图像和其他样式选项。
我做错了什么? 希望有人能帮助我:)
那么,在 onSelectChange
函数和 event.value + 1
部分中,您将添加两种不同类型的变量(字符串和整数)。因此,div 的背景样式将无法正确更改。首先,你应该像下面这样写这个函数
onSelectChange = (event) => {
this.setState({
backgroundStyle: styleOptions[parseInt(event.target.value) + 1],
});
};
那么,style{this.backgroundStyle}
应该改为style={this.state.backgroundStyle}
。我还添加了高度属性并分配了一个 backgroundColor
以使 div 和更改更明显
但也有其他小的修改。因此,请检查代码更正版本的 sandbox。