为什么 React 不缓存子组件的 html 个元素?

Why doesn't React cache html elements of child components?

你好!

我想知道下面的 React 示例有什么问题,或者 React 的工作方式是否与我想象的不同?

我正在寻找一种方法,当父组件是两个不同的组件时,为子 React 组件重用底层 html 元素。

在下面的示例中,我希望 Circle 组件内部在调用 renderC1 和 renderC2 后具有相同的元素。例如,这样我就可以应用过渡 css 属性 来为颜色切换设置动画,就像我在只是直接在元素上更改了样式。

当我渲染波纹管时,React 似乎总是生成不同的 HTML 元素,DIV 上的 ref、key 或 id(在 Circle 的渲染函数中)没有多大帮助。

所以我的问题是:是否可以让 React 在渲染 C2 时重用通过 C1 渲染的 DIV?我认为这就是 React 应该如何工作,优化底层 HTML 元素?

类似于:

var C1 = React.createClass({
  render: function () {
    return (
        <Circle background="deeppink" onClick={renderC2}/>
     );
  }
});

function renderC1 () {
  React.render(
    <C1 />, 
    document.getElementById('mount-point'));
}

var C2 = React.createClass({
  render: function () {
    return (
        <Circle background="salmon" onClick={renderC1}/>
     );
  }
});

function renderC2 () {
      React.render(
    <C2 />, 
    document.getElementById('mount-point'));
}

var Circle = React.createClass({
  styler: {
    width: "100px",
    height: "100px",
    mozBorderRadius: "50%",
    webkitBorderRadius: "50%",
    borderRadius: "50%",
    background: 'hotpink'
  },

  componentWillMount: function() {
    if (this.props && this.props.background &&
       this.props.background !== this.styler.background) {
         this.styler.background = this.props.background;
    }
  },

  render: function() {
    return (
      {/* tried adding key, ref and id, but does not reuse element */}
      <div onClick={this.props.onClick} style={this.styler}></div>
    );
  }
});

renderC1();

这是不可能的。 DOM 不允许一个元素同时出现在两个地方。尝试将 DOM 元素放在新位置会自动将其从旧位置移除。

你可以在这里看到。 (或者更形象地说,here

var parent1 = document.createElement('div'),
    parent2 = document.createElement('div'),
    child = document.createElement('div'),
    results = document.createElement('span');

  document.body.appendChild(results);
        
  parent1.appendChild(child);
  results.textContent += child.parentNode === parent1; //true
  parent2.appendChild(child);
  results.textContent += ', ' + (child.parentNode === parent1); //false