学习笔记——React Ref

由于React的单向数据流设计,所以典型的 React 数据流中, 属性(props)是父组件与子组件交互的唯一方式。要修改子组件,你需要使用新的 props 重新渲染它。但有些时候我们需要强制修改子组件,比如form表单中的validation。React提供了Ref,用于访问在render中创建的Dom元素或React组件实例。

Ref 的使用场景

  • 处理焦点、文本选择或媒体控制。
  • 触发强制动画。
  • 集成第三方 DOM 库。

Ref的定义和使用

  • 创建和访问Refs
    React提供了两种方式来创建Ref,一种是creatRef() API , 一种是ref回调。下面分别给出实例进行演示:

    • 使用React.createRef()创建
      • 当 ref 属性被用于一个普通的 HTML 元素时,React.createRef() 将接收底层 DOM 元素作为它的 current 属性以创建 ref 。
      • 当 ref 属性被用于一个自定义类组件时,ref 对象将接收该组件已挂载的实例作为它的 current 。
    class CustomInputText extends React.Component {
      constructor(props){
          super(props);
          this.inputTextRef = React.createRef();
    
          this.handleInputTextRef = this.handleInputTextRef.bind(this);
      }
    
      handleInputTextRef() {
          console.log('handle input text dom ref', this.inputTextRef)
          this.inputTextRef.current.focus();
      }
    
      render() {
          return (
            <div>
                <input
                type="text"
                ref={this.inputTextRef}/>
                <input
                type="button"
                value="Dom Ref"
                onClick={this.handleInputTextRef}/>
            </div>
          );
      }
    }
    
    • 使用Ref回调创建
      • 不同于传递 createRef() 创建的 ref 属性,你会传递一个函数。这个函数接受 React 组件的实例或 HTML DOM 元素作为参数,以存储它们并使它们能被其他地方访问。
    class ReactRefComponent extends React.Component {
      constructor(props){
          super(props);
    
          this.customInputRef = null;
    
          this.handleCustomInput = this.handleCustomInput.bind(this);
      }
    
      handleCustomInput() {
          console.log('handle custom input component ref', this.customInputRef);
          this.customInputRef.handleInputTextRef();
      }
    
      render() {
          return (
              <div>
                  <CustomTextInput ref={(ref) => this.customInputRef = ref }/>
                  <input type="button" value="Component Ref" onClick={this.handleCustomInput}/>
              </div>
          );
      }
    }
    

Forwarding Refs

  • 在实际开发中,有时可能希望能访问子组件中的DOM节点(注意是子组件中的DOM节点,而不是子组件, 且这种操作是不推荐的,因为会破坏组件的封装性),这时如果通过向子组件添加Ref,获取的依然是子组件的实例,而不是其中的DOM节点。有两种方式可以用来解决这个问题 。
    • Forwarding Refs(16.3版本以后):使得组件可以像暴露自己的Ref一样,暴露子组件的Ref。
    class CustomInputTextWithForwardRef extends React.Component {
      render() {
          return (
            <div>
                <input
                type="text"
                value={this.props.value}
                readOnly
                ref={this.props.forwardRef}/>
           </div>
          );
      }
    }
    
    export default React.forwardRef((props, ref) => {
      return <CustomInputTextWithForwardRef forwardRef={ref} {...props}/>
    });
    
    
    class ReactRefComponent extends React.Component {
      constructor(props){
          super(props);
    
          this.forwardRef = React.createRef();
          this.handleForwardRef = this.handleForwardRef.bind(this);
      }
    
      handleForwardRef() {
          console.log('handle forward ref', this.forwardRef);
          this.forwardRef.current.focus();
      }
    
      render() {
          return (
              <div>
                  <CustomInputTextWithForwardRef
                      ref={this.forwardRef}
                  />
              </div>
          );
       }
     }
    export default ReactRefComponent;
    
    • 将ref作为特殊名字的props直接传递
    function CustomTextInput(props) {
      return (
      <div>
        <input ref={props.inputRef} />
      </div>
      );
    }
    
    class Parent extends React.Component {
       constructor(props) {
         super(props);
       this.inputElement = React.createRef();
     }
       render() {
         return (
           <CustomTextInput inputRef={this.inputElement} />
         );
       }
    }
    

注意事项

  • 不能为函数式组件添加Ref,
  • String类型的Refs 存在很多问题,且已经过时, 很可能在未来的版本中移除,参见https://juejin.im/post/5b59287af265da0f601317e3#heading-2
  • ref和key属性一样,无法像props一样传递。
  • 如果 ref 回调以内联函数的方式定义,在更新期间它会被调用两次,第一次参数是 null ,之后参数是 DOM 元素。这是因为在每次渲染中都会创建一个新的函数实例。因此,React 需要清理旧的 ref 并且设置新的。通过将 ref 的回调函数定义成类的绑定函数的方式可以避免上述问题,但是大多数情况下无关紧要.
class CustomInputTextWithCallbackRefBind extends React.Component {
    constructor(props){
        super(props);

        this.inputTextRef = null;

        this.handleInputTextRef = this.handleInputTextRef.bind(this);
        this.addCustomInputRef = this.addCustomInputRef.bind(this);
    }

    handleInputTextRef() {
        this.inputTextRef.focus();
    }

    addCustomInputRef(ref) {
        this.inputTextRef = ref;
    }

    render() {
        return (
          <div>
              <input
              type="text"
              ref={this.addCustomInputRef}
              />
              <input
              type="button"
              value="callback Ref bind"
              onClick={this.handleInputTextRef}/>
          </div>
        );
    }
}

export default CustomInputTextWithCallbackRefBind;
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 4,721评论 0 1
  • 3. JSX JSX是对JavaScript语言的一个扩展语法, 用于生产React“元素”,建议在描述UI的时候...
    pixels阅读 7,939评论 0 24
  • 原教程内容详见精益 React 学习指南,这只是我在学习过程中的一些阅读笔记,个人觉得该教程讲解深入浅出,比目前大...
    leonaxiong阅读 7,860评论 1 18
  • 以下内容是我在学习和研究React时,对React的特性、重点和注意事项的提取、精练和总结,可以做为React特性...
    科研者阅读 12,580评论 2 21
  • 浩言正语117:风可以吹起一大张白纸,却无法吹走一只蝴蝶。因为,生命的力量在于不顺从。
    永远的浩子阅读 1,666评论 0 0

友情链接更多精彩内容