我打算通过悬停元素来更改内联 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>
);
}
}
还不能附加图片,所以这里是错误消息的链接。
最佳答案
在 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/