ref实现输入框聚焦

关于ref我们是怎么理解的呢?
我们可以通过React.createRef()创建一个 ref节点,并将其打印出来。
代码如下:

import React,{Component} from 'react'
import './MyRef.less'
class MyRef extends Component{
  constructor(props){
    super(props)
    this.myRef=React.createRef()
    console.log('this.myRef>>>',this.myRef)  }
  render(){
    return(
      <div ref={this.myRef}>
      </div>
    )
  }
}
export default MyRef

查看控制台我们可以看到,我们的ref取到的其实就是一个html的dom节点,或者说react元素

如果我们想实现点击按钮,输入框聚焦和页面加载进来输入框聚焦又应该怎么做呢?
(一)当我点击按钮,想要input框聚焦,这个时候的话,就是我们点击的时候要取到这个输入框节点,并且让它聚焦

代码如下

import React,{Component} from 'react'
import './MyRef.less'
class MyRef extends Component{
  constructor(props){
    super(props)
    this.textInput=React.createRef()
    }
  focusTextInput=()=>{
    this.textInput.current.focus()
  }
  render(){
    return(
      <div>
        <input 
          type="text"
          ref={this.textInput}
        />
        <input
          type="button"
          value="focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    )
  }
}
export default MyRef

(二)那如果我们想要输入框在页面加载就聚焦,我们应该怎么做呢?
React 会在组件加载时将 DOM 元素传入 current 属性,在卸载时则会改回 null。
ref 的更新会发生在componentDidMount 或 componentDidUpdate 生命周期钩子之前。
那这个时候就需要用到componentDidMount
textarea中的内容

<textarea 
    rows={4}
    placeholder="请输入您的评论"
    value={this.state.content}
    onChange={this.handleContentChange}
    className="ant-input"
    ref={(textarea)=>this.textarea=textarea}       
/>     

通过ref直接取到这个textarea的dom对象,然后再进行聚焦

componentDidMount(){
    this.textarea.focus()
  }

by我还差远了,差的很远

猜你喜欢

转载自www.cnblogs.com/smart-girl/p/10007339.html