[英]Why am I get this warning ' Mutating `style` is deprecated' in react component render?
我正在尝试在react组件渲染函数中设置一个styleObj,如下所示:
class ImgFigure extends React.Component {
render() {
let styleObj = {};
// props.arrange is a object like this { pos: { left: '0', top: '0'}}
if (this.props.arrange.pos) {
styleObj = this.props.arrange.pos;
}
return (
<figure className="img-figure" style={styleObj}>
<img src={this.props.data.imageURL} alt={this.props.data.title} />
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
</figcaption>
</figure>
);
}
}
但它警告我:
warning.js?0260:44警告:
figure
已传递一个先前已突变的样式对象。 不推荐使用变异style
。 考虑事先克隆它。 检查ImgFigure
的render
。 上一个样式:{左:0,上:0}。 变异样式:{左:519,上:272}。
我已经搜索了相关信息,并且在大多数情况下,该样式被分配为“ NaN”或添加了其他样式。 我不知道我哪里错了,你能帮我吗?
该错误很容易解释。 解决方案可能没有那么多。 这是在告诉您您已传递了对一个对象的引用,该对象自从您用let
声明它以来就可能已经发生了变异。 正确的方法是将其声明为const
。 当然,您不能重新分配它,但是没关系,因为您不应该放在第一位。
而是考虑一下:
const styleObj = this.props.arrange.pos || {};
甚至更好的是,向组件添加defaultProps
属性,并确保this.props.arrange.pos
始终至少是一个空对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.