gpt4 book ai didi

javascript - React 如何更新样式坐标

转载 作者:搜寻专家 更新时间:2023-11-01 04:23:24 25 4
gpt4 key购买 nike

每当我尝试在 React 中动态更新某些组件时,例如对象在 mousemove 上的位置,它都会抛出错误:

Warning: `div` was passed a style object that has previously been mutated. Mutating `style` is deprecated. Consider cloning it beforehand.

如果我不能以任何方式更新对象样式 Prop ,那么这怎么可能做任何类型的动态东西,比如互动游戏。至于 Reactjs 建议的克隆节点,在任何地方都没有解释如何使用克隆元素实现相同的结果。

https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

这一点用处都没有。

我的问题是,在 mouseup 事件(用户想要放下这件作品)上,我想为从更新的状态属性中获取的新值更新样式 Prop ,即在渲染函数中。

<ComponentOne style={{left: this.state.left, top: this.state.top}} />  

最佳答案

出现此警告是因为 lefttopNaN。在 getInitialState 函数 中将 left 或 top 初始化为零或某个值。

  getInitialState: function() {
return {
left:0,
top: 0
};

此外,克隆 React-Element 在这里也无济于事。警告是说您必须在更改样式对象时克隆它。可以这样做

var style1 = {myProp: "value"};
var style2 = Object.assign({}, style1, {newProp:"newValue"});

而不是直接将它们设置为

<ComponentOne style={{left: this.state.left, top: this.state.top}} /> 

这样做

var myStyle = {left: this.state.left, top: this.state.top};
<ComponentOne style={myStyle} />

然后根据您的更改克隆您的 myStyle 对象并向其添加更改后的样式属性。

关于javascript - React 如何更新样式坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35683000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com