ReactJs-TypeError:无法分配为只读对象“#<Object>”的属性“ transform”

Hao*_* Wu 5 javascript jsx reactjs

我打算通过将元素悬停来更改内联CSS。但是,由于反应异常,该类中“样式”对象的所有属性都以某种方式只读。

但是可以使用“渲染”方法对其进行修改。我搜索了错误消息,很多人通过修改props对象得到了此错误消息。但是这个错误甚至不在props对象中。有任何想法吗?

这是我的代码:

import React, { Component } from 'react';

export default class Game extends Component {
   state = {

   }

   style = {
      height: '200px',
      backgroundImage: 'url()',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      transform: 'scale(1)'
   }

   onHover() {
      this.style.transform = 'scale(1.2)';
   }

   render() {
      const { game, onClick } = this.props;
      const { img, name } = game;
      this.style.backgroundImage = `url(${img})`;
      this.style.transform = 'scale(1)';
      return (
         <div className="m-2"
            style={this.style}
            onClick={() => { onClick(this.props.game) }}
            onMouseEnter={() => this.onHover()}
         >{name}</div>
      );
   }
}
Run Code Online (Sandbox Code Playgroud)

尚无法附加图像,因此这是错误消息的链接。

错误消息截图

Bho*_*yar 4

在 React 中更新属性的唯一方法是使用 setState 更新状态。或者,您应该将它们放置在渲染钩子本身内或您需要它们的位置:

render() {
  const { game, onClick } = this.props;
  const { img, name } = game;
  const style = {
      height: '200px',
      backgroundImage: 'url()',
      backgroundSize: 'cover',
      backgroundRepeat: 'no-repeat',
      backgroundPosition: 'center',
      transform: 'scale(1)'
   }
  // now, you can modify
  style.backgroundImage = `url(${img})`;
  style.transform = 'scale(1)';
Run Code Online (Sandbox Code Playgroud)

或者,甚至您可以将它们放在类之外:(在您的情况下,这将是首选方法,因为您正在更新所需方法中的属性)

const style = {
   height: '200px',
   backgroundImage: 'url()',
   backgroundSize: 'cover',
   backgroundRepeat: 'no-repeat',
   backgroundPosition: 'center',
   transform: 'scale(1)'
}
export default class Game extends Component {
  render() {
    // modifying style
    style.backgroundImage = `url(${img})`;
    style.transform = 'scale(1)';
Run Code Online (Sandbox Code Playgroud)