关于javascript:如何不重新渲染React组件的特定DOM元素?

How to not re-render React component's specific DOM elements?

最近,我开始使用React重构我的Backbone Web应用程序,并且我试图使用react和sigma.js编写交互式图形可视化组件。

我大致了解了React的声明式范例以及使用jsx语法的render()方法如何实现它。

但是让我迷迷糊糊的是,我无法声明性地定义我的React组件。

这是由于javascript生成的DOM元素,该元素只能在由render()呈现声明性DOM元素后在componentDidMount()上生成。

这让我担心性能和错误动画(我的图形对实例化时间进行动画处理,在这种情况下,每次调用render()都会重新播放动画)

我当前的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
...

render: function() {
  return (
   
      {/*
          This div is defined declaratively, so won't be re-rendered
          on every `change` events* unless `React`'s diff algorithm
          think it needs to be re-rendered.
      */
}
      {this.props.text}

      {/*
          This div will be filled by javascript after the `render()`
          call. So it will be always cleared and re-rendered on every
          `change` events.
      */
}
     
   
  );
},

componentDidMount: function() {
  this.props.sigmaInstance.render('.graph-container', this.props.graph);
}

...

有什么办法可以做

1
2
3
4
5
6
7
8
9
10
11
12
13
render: function() {
  return (
   
      {this.props.text}

      {/*
          Any nice workaround to tell react not to re-render specific
          DOM elements?
      */
}
     
   
  );
},

这样我的sigma.js图形组件就不会在状态的每个change上都以相同的开始动画重新实例化?

由于这似乎是关于处理React组件的非声明性部分,因此将赞赏这种问题的任何解决方法。


最干净的方法是定义react子组件并重新渲染您真正需要的内容,而不是重新渲染整个块

1
2
3
4
5
6
7
8
9
10
render: function() {

    return (
       
           <SubComponentToUpdateOften/>
           <MyGraph/>
       
    )

}

另一种解决方案是处理图形并实现单例,因此动画在第一次渲染时仅播放一次。

但实际上,我看到的最简单,最干净的方法是创建干净的单独子组件,并在需要时进行更新。 您永远不会只更新subs一个大容器组件。

希望能帮助到你


您可以危险地使用SetInnerHTML。 这基本上告诉React远离它的内容,并且在进行DOM区分时不会评估/更新它。