一、适用于以下场景:

1、控制焦点,文本选择,或者媒体控制

2、触发必要的动画

3、整合第三方dom库

二、不要过度使用ref

如果想通过ref来改变state,那么换一种方式-变量提升可能会更好。

三、ref可以添加在dom中

ref接收一个回掉函数,该函数的传入参数为底层的dom元素,该回掉方法会在组件挂载后和移除后立即执行,

React 组件在加载时将 DOM 元素传入 ref 的回调函数,在卸载时则会传入 nullref回调会在componentDidMount 或 componentDidUpdate 这些生命周期回调之前执行。

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    // 直接使用原生 API 使 text 输入框获得焦点
    this.textInput.focus();
  }

  render() {
    // 使用 `ref` 的回调将 text 输入框的 DOM 节点存储到 React 
    // 实例上(比如 this.textInput)
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

 

四、ref添加在组件实例中

当 ref 属性用于使用 class 声明的自定义组件时,ref 的回调接收的是已经加载的 React 实例

class AutoFocusTextInput extends React.Component {
  componentDidMount() {
//所以此时相当于调用了CustomTextInput的focusTextInput()方法
    this.textInput.focusTextInput();
  }

  render() {
    return (
      <CustomTextInput
//在这里定义this.textInput的值为input即为CustomTextInput组件的实例
        ref={(input) => { this.textInput = input; }} />
    );
  }
}

五、对父组件暴漏dom节点

function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

function Parent(props) {
  return (
    <div>
      My input: <CustomTextInput inputRef={props.inputRef} />
    </div>
  );
}


class Grandparent extends React.Component {
  render() {
    return (
      <Parent
        inputRef={el => this.inputElement = el}
      />
    );
  }
}

可以通过中间属性来传递回掉函数,进而访问子组件中的dom

 

参考:https://doc.react-china.org/docs/refs-and-the-dom.html

           https://reactjs.org/docs/refs-and-the-dom.html

posted on 2018-03-08 22:18  爬虫一只  阅读(410)  评论(0编辑  收藏  举报