React 与 DOM
1. ReactDOM
ReactDOM 中的 API 非常少,只有 findDOMNode 、 unmountComponentAtNode 和 render 。
- findDOMNode
DOMElement findDOMNode(ReactComponent component)
当组件被渲染到 DOM 中后, findDOMNode 返回该 React 组件实例相应的 DOM 节点
例,假设要在当前组件加载完时获取当前 DOM,则可以使用 findDOMNode
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class App extends Component {
componentDidMount() {
// this 为当前组件的实例
const dom = ReactDOM.findDOMNode(this);
}
render() {}
}
findDOMNode 只对已经挂载的组件有效。
- render
把React 渲染的Virtual DOM 渲染到浏览器的 DOM 当中
ReactComponent render(
ReactElement element,
DOMElement container,
[function callback]
)
该方法把元素挂载到 container 中,并且返回 element 的实例(即 refs 引用)
refs
refs可依附任何组件。组件被调用时会新建一个该组件的实例,而 refs 就会指向这个实例
refs可为回调函数,在组件被挂载后立即执行,例
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
if (this.myTextInput !== null) {
this.myTextInput.focus();
}
}
render() {
return (
<div>
<input type="text" ref={(ref) => this.myTextInput = ref} />
<input
type="button"
value="Focus the text input"
onClick={this.handleClick}
/>
</div>
);
}
}
点击按钮聚焦到input框
为了防止内存泄漏,当卸载一个组件的时候,组件里所有的 refs 就会变为 null