我理解的虚拟DOM

来源:互联网 发布:官方刷机软件 编辑:程序博客网 时间:2024/06/05 17:29

react中的组件(React.Component的实例)并不是真实的dom节点,是存在于内存中的一种数据结构,叫做虚拟DOM。
组件在呈现的过程中,先根据render返回的结果将这个树状结构(虚拟DOM)在js中创建出来,这个时候并没有操作DOM,然后比对新老虚拟DOM,渲染成实际的DOM。在react的设计中,所有DOM的变动,都现在虚拟DOM上发生,然后将实际发生变动的部分反映在真实的DOM上。

题外话:
有时候需要从组件中获取真实的DOM节点,这个时候用到ref属性:
refs属性采用回调函数的方式,在组件mounted/unmounted时触发。

class CustomTextInput extends React.Component {  constructor(props) {    super(props);    this.focus = this.focus.bind(this);  }  focus() {    // Explicitly focus the text input using the raw DOM API    this.textInput.focus();  }  render() {    // Use the `ref` callback to store a reference to the text input DOM    // element in an instance field (for example, this.textInput).    return (      <div>        <input          type="text"          ref={(input) => { this.textInput = input; }} />        <input          type="button"          value="Focus text input"          onClick={this.focus}        />      </div>    );  }}
原创粉丝点击