简体   繁体   English

如何使用选择框更改 div 的背景样式?

[英]How can I change background-style of div with a selection box?

On my current project in React I need to have the possibility to change the background-style (image, width, height etc.) from a 'div' to nine different options.在我当前的 React 项目中,我需要能够将背景样式(图像、宽度、高度等)从“div”更改为九个不同的选项。

I've tried it with following code:我已经使用以下代码进行了尝试:

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
            ...
            ...
         </>
      )
   }
}

But on any change from my selection field, there isnt happening anything to the background of the specific div.但是在我的选择字段发生任何变化时,特定 div 的背景不会发生任何变化。 When I put "styleOptions[x]" for x every index possible, I get the specific background image and other style options.当我为每个可能的索引添加“styleOptions [x]”时,我得到了特定的背景图像和其他样式选项。

What am I doing wrong?我究竟做错了什么? Hope someone can help me:)希望可以有人帮帮我:)

Well, in the onSelectChange function and in the event.value + 1 part you are adding two different types of variables (string and integer).好吧,在onSelectChange function 和event.value + 1部分中,您添加了两种不同类型的变量(字符串和整数)。 As a result the background styles of div would not change properly.因此div的背景styles不会正确改变。 First, you should write this function as below首先,你应该写这个 function 如下

onSelectChange = (event) => {
    this.setState({
      backgroundStyle: styleOptions[parseInt(event.target.value) + 1],
    });
  };

Then, style{this.backgroundStyle} should be changed to style={this.state.backgroundStyle} .然后, style{this.backgroundStyle}应更改为style={this.state.backgroundStyle} I also added the height attributes and assigned a backgroundColor to make the div and changes more visible我还添加了 height 属性并分配了backgroundColor以使 div 和更改更加可见

But there were also other minor modifications.但也有其他一些小的修改。 So, check the sandbox of the corrected version of your code.因此,请检查代码更正版本的沙箱

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM