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

问题描述

在我当前的 React 项目中,我需要将背景样式(图像、宽度、高度等)从“div”更改为九个不同的选项。

我已经用以下代码试过了:

const styleOptions = [
  {
    backgroundImage: "",backgroundRepeat: "no-repeat",backgroundPosition: "center",//backgroundSize: "650px 800px",backgroundSize: "cover"
  },{
    backgroundImage: "url(/PicturesPattern/Picture1.png)",...//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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...