react学习笔记(三)获取焦点的2种方式

本文介绍在React中如何在组件更新后保持输入框的焦点,防止因状态或属性变化而丢失焦点。通过两种方法实现:使用React.createRef()创建ref引用和通过函数回调获取DOM元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在React中,只要props或state发生改变,则render()方法必定执行,即DOM会更新。然React更新DOM时,可能会导致已经获取焦点的元素失去焦点,故此时需要操作DOM,获取焦点。

方式一:

React.createRef()

使用React.createRef()方法可以创建一个存储dom的ref,当ref设置在组件上时,即可存储该元素的dom引用。

// index.js
import React from 'react'
import CustomTextInput from './CustomTextInput'

class Parent extends React.Component {
  constructor(props) {
    super(props);
    // 创建一个ref存储dom元素
    this.inputElement = React.createRef();
    this.getFocus = this.getFocus.bind(this)
  }

  getFocus() {
    this.inputElement.current.focus()
  }

  render() {
    return (
      <CustomTextInput
        inputRef={this.inputElement}
        inputGetFocus={this.getFocus}
      />
    )
  }
}

export default Parent
// CustomTextInput.js
import React from 'react'

const CustomTextInput = (props) => {
  return (
    <React.Fragment>
      <input
        type="text"
        ref={props.inputRef}
      />
      <button onClick={props.inputGetFocus}>获取焦点</button>
    </React.Fragment>
  )
}

export default CustomTextInput

方式二:

使用函数

// index.js
import React from 'react'
import CustomTextInput from './CustomTextInput'

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.getInputElement = this.getInputElement.bind(this)
    this.getFocus = this.getFocus.bind(this)
  }

  getFocus() {
    this.inputElement.focus()
  }

  getInputElement(el) {
    this.inputElement = el
  }

  render() {
    return (
      <CustomTextInput
        inputRef={this.getInputElement}
        inputGetFocus={this.getFocus}
      />
    )
  }
}

export default Parent
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值