【发布时间】:2019-02-08 02:44:06
【问题描述】:
我打算通过悬停元素来更改内联 css。 但是反应吓坏了,因为这个类中“样式”对象的所有属性都是只读的。
但是可以在'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>
);
}
}
还不能附加图片,所以这里是错误消息的链接。
【问题讨论】:
-
“样式”是否可能是组件的保留属性,因此被视为只读?抱歉,我以前没有见过这个只读问题,所以我很好奇将“样式”重命名为其他内容是否可行。
-
不幸的是,这是我尝试的第一件事,但没有奏效。我在下面的 Bhojendra Rauniyar 的回答中发现了这一点。谢谢
标签: javascript reactjs jsx