【React】组件实例的三大属性——ref

1.字符串形式的ref

class Demo extends React.Component {
  // 自定义函数要用箭头函数,才能拿到正确的this
  showDlg = () => {
    const input = this.refs.input1
    alert(input.value)
  }
  showDlg2 = () => {
    const input = this.refs.input2
    alert(input.value)
  }

  render() {
    return (
      <div>
        <input ref="input1" type="text" placeholder="点击按钮弹出内容" />&nbsp;
        <button onClick={this.showDlg}>点击弹出内容</button>&nbsp;
        <input ref="input2" type="text" placeholder="失焦弹出内容" onBlur={this.showDlg2} />
      </div>  
    )
  }
}
ReactDOM.render(<Demo />, document.getElementById('test1'))

笔记:

  1. 定义:ref=“input” 接收:this.refs.input
  2. 字符串方式的ref是最简单的,但是react官方不推荐使用,因为页面上定义多了的话会有效率问题,而且可能会在之后的版本被弃用.

2.回调函数形式的ref

class Demo extends React.Component {
  state = { isHot: true }

  // 自定义函数要用箭头函数,才能拿到正确的this
  showDlg = () => {
    alert(this.input1.value)
  }
  showDlg2 = () => {
    alert(this.input2.value)
  }

  getInptEl = (el) => {
    this.input2 = el
  }

  render() {
    const { isHot } = this.state
    return (
      <div>
        {/* 内联函数式的ref */}
        <input ref={el => this.input1 = el} type="text" placeholder="点击按钮弹出内容" />&nbsp;
        <button onClick={this.showDlg}>点击弹出内容</button>&nbsp;
        
        {/* 外联函数式的ref */}
        <input ref={this.getInptEl} type="text" placeholder="失焦弹出内容" onBlur={this.showDlg2} />
      </div>
    )
  }
}
ReactDOM.render(<Demo />, document.getElementById('test1'))

笔记:
1. 回调函数的形式有两种:一种是内联函数ref={el => this.input1 = el};另一种外联的,声明ref={this.getInptEl},接收getInptEl = (el) => { this.input2 = el }
2. 通常项目中都是采用内联回调的方式.
3. 内联回调在更新的时候会有一点点问题:会被调用两次,第一次拿到的el是null,但是官方说这个影响是无关紧要的.
4. 外联样式没有什么问题,但是比较麻烦,代码不够直观 ===> 项目中使用内联回调式就行!!

3.使用createRef

class Demo extends React.Component {
  input1 = React.createRef()
  input2 = React.createRef()

  showDlg = () => {
    // current是固定的
    const input = this.input1.current
    alert(input.value)
  }
  showDlg2 = () => {
    const input = this.input2.current
    alert(input.value)
  }

  render() {
    return (
      <div>
        <input ref={this.input1} type="text" placeholder="点击按钮弹出内容" />&nbsp;
        <button onClick={this.showDlg}>点击弹出内容</button>&nbsp;
        <input ref={this.input2} type="text" placeholder="失焦弹出内容" onBlur={this.showDlg2} />
      </div>  
    )
  }
}
ReactDOM.render(<Demo />, document.getElementById('test1'))

笔记:
1. 定义:ref={this.input1}
2. 接收:input1 = React.createRef()
3. 取值:this.input2.current
4. React.createRef是官方推荐使用的API,注意拿到的DOM是在ref的current属性里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值