点击事件获取不到ref_React - ref

reference 引用

function A (){
    return (<h1>组件AAA</h1>)
}
​
<A ref="comA" />   // 不可这样使用,但是函数组件内部是可以使用ref的

过时方式(不要使用)

以聚焦input事件为例,以前的ref使用方式,ref 值为string已经过时,随时可能被移除(不建议使用,在16版中已不再可用)

export default class RefComp extends React.Component {
    
  render() {
    
    return (
      <div>
        <input ref="text" type="text" />
        <button
          onClick={() => {
    
            console.log(this);
            this.refs.text.focus()
          }}>点击 </button>
      </div>
    );
  }
}

ref值的两种形式

ref 的值根据节点的类型而有所不同:
  • ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其 current 属性。
  • ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性。
  • 你不能在函数组件上使用 ref 属性,因为他们没有实例。

1.使用React.createRef() 创建( React 16.3 版本引入)

1.1 html 组件

export default class RefComp extends React.Component {
    
  con
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值