React基础-ref总结

一、三个形式

1,字符串形式

通过实例身上的refs来调用,如下代码中的this.refs.input1来调用,这个input1是自己定义的字符串形式。

优点:最简单

缺点:新版本可能不能使用

<script type="text/babel">
    class Demo extends React.Component{
      showInput1 = () => {
        console.log(this);
        const {input1} = this.refs
        alert(input1.value)
      }
      showInput2 = () => {
        const {input2} = this.refs
        alert(input2.value)
      }
      render(){
        return (
          <div>
            <input type="text" placeholder="提示信息" ref="input1"/>
            <button onClick={this.showInput1}>点我展示左侧输入框信息</button>
            <input type="text" onBlur={this.showInput2} placeholder="失去焦点提示信息" ref="input2"/>  
          </div>
        )
      }
    }
    ReactDOM.render(<Demo/>,document.getElementById('test'))
  </script>

 2,回调函数形式

ref={c=>this.input1=c}。这是简写形式。完整形式是ref={(currentNode)=>{this.input1=currentNode}},c是currentNode的简写,代表当前input输入框的节点。这里的input1是直接挂载在组件实例身上的,调用的时候直接通过this.input1来调用3

<script type="text/babel">
    class Demo extends React.Component{
      showInput1 = () => {
        console.log(this);
        alert(this.input1.value)
      }
      showInput2 = () => {
        const {input2} = this
        alert(input2.value)
      }
      render(){
        return (
          <div>
            <input type="text" placeholder="提示信息" ref={c=>this.input1=c}/>
            <button onClick={this.showInput1}>点我展示左侧输入框信息</button>
            <input type="text" onBlur={this.showInput2} placeholder="失去焦点提示信息" ref={c=>this.input2=c}/>  
          </div>
        )
      }
    }
    ReactDOM.render(<Demo/>,document.getElementById('test'))
  </script>

3,createRef形式

第一步:创建myRef1 = React.createRef()

第二步:ref={this.myRef1}

第三步:给组件实例身上挂载了myRef1,这个myRef1是一个对象,键是current,值是当前节点。

showData1 = () =>{

        alert(this.myRef1.current.value)

      }

<script type="text/babel">
    class Demo extends React.Component{
      myRef1 = React.createRef()
      myRef2 = React.createRef()
      showData1 = () =>{
        alert(this.myRef1.current.value)
      }
      showData2 = () =>{
        alert(this.myRef2.current.value)
      }
      render(){
        return (
          <div>
            <input type="text" placeholder="提示信息" ref={this.myRef1}/>
            <button onClick={this.showData1} >点击提示左侧信息</button>
            <input type="text" placeholder="失去焦点提示数据" onBlur={this.showData2} ref={this.myRef2}/>
          </div>
        )
      }
    }
    ReactDOM.render(<Demo/>,document.getElementById('test'))
  </script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值