簡體   English   中英

為什么我在React組件渲染中收到此警告“不贊成使用可變樣式”?

[英]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 考慮事先克隆它。 檢查ImgFigurerender 上一個樣式:{左: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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM