React-refs-5

1、ref 即 reference , 组件被调用时会新建一个该组件的实例, 而 refs 就会指向这个实例

ref 使用场景

1、处理焦点、文本选择或媒体控制
2、触发强制动画
3、继承第三方 DOM 库

2、创建 ref : React.createRef()

class MyApp extends Component {
  constructor( props ){
    super( props );
    /* 创建 ref  */
    this.myRef = React.createRef();
  }
  render(){
    return <div ref={ this.myRef } />
  }
}

3、访问 ref

current :当 ref 属性被传递给一个 render() 函数中的元素时, 可以使用 ref 中的 current 属性对节点的引用进行访问

const nodeList = this.myRef.current;

ref的值取决于节点的类型

· 当 ref 属性被用于普通的 HTML 元素时, React.createRef() 将接收底层 DOM 元素作为它的 current 属性创建 ref

 class Parent extends Component {
  constructor( props ){
    super( props );
    this.ipt = React.createRef();
    this.focusTextInput = this.focusTextInput.bing( this );
  }
  render(){
  {/* 为 DOM 元素添加 ref */}
    return <input type="text" ref={ this.ipt } onClick={ this.focusTextInput }/>
  }
  focusTextInput(){
    this.ipt.current.focus();
  }
};

· 当 ref 属性被用于自定义类组件时, ref 对象将接收该组件已挂载的实例作为它的current

class Counter extends Component {
  constructor( props ){
    super( props );
    this.textInput = React.createRef();
  }
  componentDidMount(){ // 页面挂载后立即获取焦点
    this.textInput.current.focusTextInput();
  }
  render(){
   {/*为类组件添加 ref*/}
    return <CustomTextInput ref={ this.textInput } />
  // return <CustomTextInput ref={ (this.textInput) => this.textInput.current.focus(); } />
  }
  focusTextInput(){
    this.textInput.current.focus();
  }
}

· 函数式组件上不能使用 ref 属性, 因为它们没有实例, 如果想使用 ref 应该将其转换为 calss 组件

function MyCreateComponent(){ 
  return <input />;
};
  class Parent extends Component {
    cosntructor( props ){
    super( props );
    this.ipt = React.createRef();
  }
  render(){
    { /* 
    	不能在函数式组件上使用 ref 属性,
    	函数组件中的 ref 引用是无效的, 这将不会工作 
    */ }
    return <MyCreateComponent ref={ this.ipt } />
  }
};

· 或者在函数式组件内部使用 ref , 只要它指向 DOM 元素或者 class 组件

function CustomText(){
  let textInput = null;   // let 变量绑定所在作用域
  function handleClick(){ // 焦点事件
    textInput.focus();
  }
  return (
    <div>   // 箭头函数绑定所定义的环境 this 指向 组件本身
      <input type="text" ref={ ( el ) => textInput = el } />
      <input type="button" onClick={ handleClick }>
    </div>
  )
}

4、ref 可以是一个回调函数, 这个回调函数会在组件被挂载后立即执行

不同于传递 createRef() 创建的 ref 属性。这是传递一个函数。这个函数接受 React 组件的实例或 HTML DOM 元素作为参数,以存储它们并使它们能被其他地方访问

import React from 'react';
class App extends Component {
  constructor( props ){
    super( props );
    this.textInput = el => this.ipt = el;
  }
  render(){
    return <input type="text" ref={ this.textInput } />
    // 等价于
    // return <input type="text" ref={ ( el ) => this.ipt = el } />
  }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值