React的ref使用方法

何时使用 Refs
下面是几个适合使用 refs 的情况:

  1. 管理焦点,文本选择或媒体播放。
  2. 触发强制动画。
  3. 集成第三方 DOM 库。

ref的三种使用方法

  1. 字符串(官网不推荐使用)
  2. 回调ref
class Demo extends React.Component{
  render () {
    return (
      <div>
        <input type="text" ref={el =>{ this.input1 = el}}></input>
        <button onClick={this.show}>点我显示数据</button>
        <input type="text" onBlur={this.show2} ref={ el => this.input2 = el}></input>
      </div>
    )
  }
  show = () => {
    const { input1} = this
    alert(input1.value)
  }
  show2 = () => {
    const { input2} = this
    alert(input2.value)
  }
}
复制代码
  1. React.createRef()创建
  • 当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。
  • 当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性。
  • 不能在函数组件上使用 ref 属性。
class Test extends React.Component{
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render () {
    return (
      <div>
        <input type="text" onBlur={this.show} ref={ this.myRef }></input>
      </div>
    )
  }
  show = () => {
    const { myRef} = this
    alert(myRef.current.value)
  }
}

复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享