当元素改变其在DOM中的位置时,有可能得到移动元素的响应,而不是重新创建元素?
让我们假设我正在制作一个2窗格组件,并且我希望能够隐藏/取消隐藏一个窗格。让我们也想象一下窗格本身是非常沉重的。在我的例子中,每个窗格都有2000多个元素。
在我的实际代码中,当有两个窗格时,我使用一个拆分器。为了只显示一个窗格,我需要删除拆分器并用div替换它。
下面的代码模拟了这一点。如果有一个窗格,它将使用div来包含该窗格。如果有两个窗格,它就使用pre来包含它们。在我的例子中,它将是带有1痛的div和带有2的splitter。
因此,在对document.createElement进行检测时,我看到不仅创建了容器,而且重新创建了内部的元素。换句话说,在我的代码中,当从拆分器->div离开时,2000+元素窗格将被完全重新创建,这是缓慢的。
有什么办法能让我们有效地反应。“嘿,不要再创建这个组件,只要移动它?”
class TwoPanes extends React.Component {
constructor(props) {
super(props);
}
render() {
const panes = this.renderPanes();
if (panes.length === 2) {
return React.createElement('pre', {className: "panes"}, panes);
} else {
return React.createElement('div', {className: "panes"}, panes);
}
}
renderPanes() {
return this.props.panes.map(pane => {
return React.createElement('div', {className: "pane"}, pane);
});
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
panes: [
"pane one",
"pane two",
],
};
}
render() {
const panes = React.createElement(TwoPanes, {panes: this.state.panes}, null);
const button = React.createElement('button', {
onClick: () => {
const panes = this.state.panes.slice();
if (panes.length === 1) {
panes.splice(0, 0, "pane one"); // insert pane 1
} else {
panes.splice(0, 1); // remove pane 1
}
this.setState({panes: panes});
},
}, "toggle pane one");
return React.createElement('div', {className: "outer"}, [panes, button]);
}
}
// wrap document.createElement so we can see if new elements are created
// vs reused
document.createElement = (function(oldFn) {
let count = 0;
let inside = false;
return function(type, ...args) {
if (!inside) { // needed because SO's console wrapper calls createElement
inside = true;
console.log(++count, "created:", type);
inside = false;
}
return oldFn.call(this, type, ...args);
}
}(document.createElement));
ReactDOM.render(
React.createElement(App, {}, null),
document.getElementById('root')
);html { box-sizing: border-box; }
*, *:before, *:after { box-sizing: inherit; }
body { margin: 0; }
#root { width: 100vw; height: 100vh; }
.outer {
width: 100%;
height: 100%;
}
.panes {
width: 100%;
height: 100%;
display: flex;
flow-direction: row;
justify-content: space-between;
}
.pane {
flex: 1 1 auto;
border: 1px solid black;
}
button {
position: absolute;
left: 10px;
top: 30px;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
发布于 2016-12-13 15:35:37
我不认为有一种方法可以在DOM树周围移动,即使有,它也会非常昂贵,因为
O(n)中运行所做的假设之一。不同类型的两种元素会产生不同的树。
DOM中移动,首先需要将它从树中分离出来,这意味着以后还需要重新应用它,这是一个瓶颈。将HTML插入DOM是非常昂贵的,即使缓存/预录制也是如此。我的建议是使用CSS,因为display: none / display: block比重新应用缓存的DOM快得多。
class TwoPanes extends React.Component {
render() {
return (
<div>
<Pane1 />
<Pane2 style={this.state.panes.length === 2 ? {} : {display: 'none'} } />
</div>
);
}
}https://stackoverflow.com/questions/41124310
复制相似问题