javascript - ReactJs - 类型错误 : Cannot assign to read only property 'transform' of object '#<Object>'

标签 javascript reactjs jsx

我打算通过悬停元素来更改内联 CSS。 但是 react 吓坏了,因为这个类中“style”对象的所有属性都是只读的。

但是在'render'方法中修改它就可以了。 我搜索了错误信息,很多人通过修改 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>
      );
   }
}

还不能附加图片,所以这里是错误消息的链接。

Error message screenshot

最佳答案

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

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)';

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

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)';

关于javascript - ReactJs - 类型错误 : Cannot assign to read only property 'transform' of object '#<Object>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52143027/

相关文章:

另一个脚本启动后 Javascript 失败

javascript - 设置 Canvas 背景颜色

javascript - 对于如何在 React 组件中的条件语句中返回,是否有解决方法?

javascript - 在 `state.tree` 中写入 `state.xxxReducer.tree` 而不是 `mapStateToProps` (react redux)

javascript - 看似相等的物体其实并不相等

javascript - 我应该完全停止使用内联 JavaScript 吗?

javascript - 是否有将 React Elements javascript 代码转换为 JSX 的工具

javascript - Sweet Alert 中使用 JSX 代替 HTML

javascript - es6 箭头函数中的花括号代表每个

javascript - 为什么 -1 是假的? - 为了 (