我打算通过悬停元素来改变内联css。但反应吓坏了,因为这个类中'style'对象的所有属性都是以某种方式读取的。
但是可以在'render'方法中修改它。我搜索了错误信息,很多人通过修改道具对象得到这个错误信息。但是这个甚至不在道具对象中。有任何想法吗?
这是我的代码:
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更新状态。或者,您应该将它们放在渲染钩子本身或您需要它们的位置:
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)';