【问题标题】:How can I change background-style of div with a selection box?如何使用选择框更改 div 的背景样式?
【发布时间】: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


    【解决方案1】:

    好吧,在onSelectChange 函数和event.value + 1 部分中,您添加了两种不同类型的变量(字符串和整数)。结果 div 的背景样式不会正确更改。首先,你应该把这个函数写成如下

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

    然后,style{this.backgroundStyle} 应更改为 style={this.state.backgroundStyle}。我还添加了 height 属性并分配了 backgroundColor 以使 div 和更改更加可见

    但也有其他一些小的修改。因此,请检查您的代码更正版本的sandbox

    【讨论】:

    • 如果它解决了您的问题或需要更多改进,请告诉我
    • 感谢您的回答。当我将状态选项更改为“backgroundStyle:styleOptions [x]”时,它会显示我为“x”输入的背景。但是当我用我的 selectionField 更改它时,它仍然不会以某种方式改变我的背景......
    • 刚刚更新了答案,我尝试通过点击按钮来改变样式。我不知道您的真实代码是如何工作的,但在这个简单的示例中,您可以轻松更改背景样式。请检查它并告诉我它是否适合您
    • 我发现我的错误...当您查看代码时,该状态称为“backgroundStyle”,在 onSelectChange 函数中,我为它输入了另一个名称,“currentStyle” .完全忘了我改了名字...非常感谢您的帮助!
    • 不客气。您能否将我的答案标记为您问题的正确答案?
    猜你喜欢
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 2011-09-24
    • 1970-01-01
    相关资源
    最近更新 更多