0

我试图在悬停元素(图标)时更改背景图像状态,但我总是收到错误“TypeError:无法读取未定义的属性“图标””,这很奇怪,因为图标工作正常,直到我悬停它。

很高兴有人能提供帮助。

状态:

this.state = {
      images: {
        header: "path to img",
        icon: "path to icon"
      }
}

方法:

 handleMouseOver = () => {
    this.setState({
      images: {
        header: "new img"
      }
    });
  };

接收图片的头部组件:

<Header bgImg={this.state.images.header} />

悬停元素:

<div>
   <img onMouseOver={this.handleMouseOver} src={this.state.images.icon} />
</div>
4

2 回答 2

3

此问题来自您的onMouseOver函数,该函数为状态设置了一个新值,但从图像对象中删除了图标。您需要运行以下命令:

 handleMouseOver = () => {
    this.setState((state, props) => {
      return {
         images: {
           header: "new img",
           icon: state.images.icon
         }
      };
    });
  };
于 2019-10-29T12:57:31.067 回答
2

这是因为当你设置你的时候,images你正在失去icon状态。试试这样:

handleMouseOver = () => {
  this.setState(prevState => ({
    images: {
      ...prevState.images,
      header: "new img"
    }
  }));
};

images通过传播它来使用旧的,然后更新必要的属性。为什么我们使用setState回调和prevState?因为当我们设置新状态时,我们依赖于旧状态。

于 2019-10-29T13:00:52.307 回答