### 1.为DOM元素添加Ref react支持一个ref属性,该属性可以添加到任何的组件上。该ref属性接收一个回调函数,这个回调函数在组件挂载或者卸载的时候被调用。当ref用于一个HTML元素的时候,ref指定的回调函数在调用的时候会接收一个参数,该参数就是指定的DOM元素。如下面的例子使用ref回调函数来保存对DOM节点的引用: ```js 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 (
Uncaught TypeError: this.textInput.focus is not a function
at AutoFocusTextInput.componentDidMount (:24:22)
### 3.Ref与函数式声明组件
你不能在函数式声明组件中使用ref,因为他们*不存在实例*,如下面的例子就是错误的:
```js
function MyFunctionalComponent() {
return ;
}
class Parent extends React.Component {
render() {
// This will *not* work!
return (