[英]ReactJs - TypeError: Cannot assign to read only property 'transform' of object '#<Object>'
我打算通過懸停元素來更改內聯 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> ); } }
還不能附加圖片,所以這是錯誤消息的鏈接。
在 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)';
您可以復制樣式對象並更改副本:
render() {
const { game, onClick } = this.props;
const { img, name } = game;
// make a copy
let changedStyle = {
...this.style
}
// change the copy
changedStyle.backgroundImage = `url(${img})`;
changedStyle.transform = 'scale(1)';
return (
<div className="m-2"
style={changedStyle}
onClick={() => { onClick(this.props.game) }}
onMouseEnter={() => this.onHover()}
>{name}</div>
);
}
為了使它更干凈,您可以通過以下方式合並 css 類
style = {
height: '200px',
backgroundImage: 'url()',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center',
transform: 'scale(1)',
}
hoveringStyle = {
transform: 'scale(1.2)',
}
this.style = {...style, ...hoveringStyle}
這可能會產生我不知道的負面影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.