react ref的用法

本文详细介绍了React中ref的三种使用方式:字符串引用、回调函数引用和React.createRef API。通过实例展示了如何在不同版本的React中获取并使用DOM元素,特别是在组件生命周期中的应用。同时,讨论了最佳实践,推荐使用React.createRef。
摘要由CSDN通过智能技术生成

ref的3种用法:

在 React v16.3 之前,ref 通过字符串(string ref)或者回调函数(callback ref)的形式进行获取。

  • ref 通过字符获取:
// string ref
class MyComponent extends React.Component {
 componentDidMount() {
   this.refs.myRef.focus();
 }

 render() {
   return <input ref="myRef" />;
 }
}
  • ref 通过回调函数获取:
// callback ref
class MyComponent extends React.Component {
  componentDidMount() {
    this.myRef.focus();
  }
 
  render() {
    return <input ref={(ele) => {
      this.myRef = ele;
    }} />;
  }
}

在 v16.3 中,经 0017-new-create-ref 提案引入了新的 API:React.createRef。

  • ref 通过 React.createRef 获取:
// React.createRef
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
 
  componentDidMount() {
    this.myRef.current.focus();
  }
  
  render() {
    return <input ref={this.myRef} />;
  }
}

参考链接:

参考链接

能力上最好的方法是用回调函数

JS与jQuery对象之间的转换

1、js对象转换成jquery对象。 $(js对象);

2、jquery对象转换成js对象。 (1)jquery对象[索引值] (2)jquery对象.get(索引值)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值