[英]Object becomes read-only after the component rendered first time
The issue occurs when I try to upgrade React 15.X to React 16.X:当我尝试将 React 15.X 升级到 React 16.X 时会出现问题:
let style = {
width:12
};
class Box extends React.Component {
constructor(props) {
super(props);
}
render() {
console.log(Object.getOwnPropertyDescriptor(style,'width'))
style.width = 96;
return (
<div style={style}>
</div>
);
}
}
outputs:输出:
- {value: 12, writable: true , enumerable: true, configurable: true}
{值:12,可写:真,可枚举:真,可配置:真}
- {value: 12, writable: false , enumerable: true, configurable: false}
{值:12,可写:假,可枚举:真,可配置:假}
- {value: 12, writable: false, enumerable: true, configurable: false}
{值:12,可写:假,可枚举:真,可配置:假}
Anyone knows why the 'writable' becomes false?任何人都知道为什么“可写”会变成假?
Because mutating the style
object is forbidden, and somewhere in the rendering process, Object.freeze(style)
is called.因为改变
style
对象是被禁止的,并且在渲染过程的某个地方, Object.freeze(style)
被调用。
Ref:参考:
Object mutation in React has long been discouraged.长期以来,React 中的对象突变一直不被鼓励。
Object.freeze(props)
is enforced back in v0.xx days. Object.freeze(props)
在 v0.xx 天后被强制执行。 In v16 Object.freeze(style)
is added.在 v16 中添加了
Object.freeze(style)
。
Try use 尝试使用
<div style={this.style}>
For me its working after using this 对我来说使用它后的工作
Update 更新资料
If I'm not wrong you want to effect your style after dynamically change, in this case you have to use state, Here is my idea 如果我没看错,您想在动态更改后影响样式,在这种情况下,您必须使用状态,这是我的想法
You have to declare state for your style like this 您必须像这样声明自己的风格状态
class Box extends React.Component {
state = {
style: {
width: 12
}
}
Here is my render
这是我的
render
render() {
console.log(Object.getOwnPropertyDescriptor(this.state.style, "width"));
return (
<div style={this.state.style}>
<button onClick={this.handleChangeStyle}>Change Style</button>
</div>
);
}
And here is my handle method 这是我的处理方法
handleChangeStyle = () => {
let style = { ...this.state.style };
style.width += 1;
this.setState({ style });
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.