这就是我正在做的:jsfiddle
关键部分是:
position: function() {
var container = $(this.getDOMNode());
this._menu = $(this.refs.menu.getDOMNode());
this._menu.appendTo(document.body).
offset({
top: container.offset().top +
container.outerHeight(),
left: container.offset().left
});
},
restore: function() {
this._menu.appendTo(this.getDOMNode());
},
componentWillUpdate: function() {
this.restore();
},
componentDidUpdate: function() {
this.position();
},
componentDidMount: function() {
this.position();
},
现在效果很好。我在组件更新之前将内容放回原处,假设 React 在更新之间保持 DOM 独立并且不会错过它。事实上,React 似乎可以很好地处理移动内容(如果我删除 componentWillUpdate
和 componentDidUpdate
,定位的元素仍然会更新!)
我的问题是由此产生的假设中有多少是安全的(即,如果我假设这些事情,我的代码会在未来版本的 React 中崩溃吗?):
- React 并不关心 DOM 是否在更新之间移动,只要将其放回
componentWillUpdate
即可。 - React 事件处理程序仍将对已移动的元素起作用。
- React 会将您要求的任何内联样式与元素上已有的样式合并(即使它没有设置它们。)
- React 会更新它所渲染的 DOM,即使您将该 DOM 移动到文档中的其他位置!
最后一个对我来说似乎有点极端和神奇,但如果它成立的话会有一些重大影响。
最佳答案
我是一名 React 开发者。我将回答您的每个问题:
<小时/>React does not care if DOM is moved around between updates as long as you put it back in componentWillUpdate.
True - React 不会查看 DOM,除非更新,事件处理程序除外:
React event handlers will still work on elements that have been moved.
我不会依赖这一点,而且我现在也不确定它是否属实。
React will merge any inline styles you ask it with styles already on the element (even if it did not set them.)
我也不会依赖于此——现在 React 设置了单独的属性,但我可以很容易地想象它设置 el.style.cssText
如果速度更快,这会破坏您所做的个别更改。
React will update DOM it has rendered, even if you move that DOM somewhere else in the document!
我目前认为这不是真的,您也不应该依赖这一点。
<小时/>一般来说,您不应该手动操作 React 创建的 DOM。创建一个空的 <div>
是 100% 干净的在 React 中并手动填充它;甚至可以修改 React 渲染元素的属性,只要您稍后不尝试在 React 中更改其属性(导致 React 执行 DOM 更新),但如果您移动一个元素,React 可能会查找它并当找不到它时会感到困惑。
关于dom - react : How much can I manipulate the DOM React has rendered?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23530716/