zoukankan      html  css  js  c++  java
  • 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我还差远了,差的很远

  • 相关阅读:
    Visual Studio 2019 XAML Hot Reload功能介绍
    C#开启和关闭UAC功能
    使用Powershell启用/关闭Windows功能
    解决C#调用COM组件异常来自 HRESULT:0x80010105 (RPC_E_SERVERFAULT)的错误
    ComPtr的介绍以及使用
    C#使用Selenium
    estimateAffinePartial2D 替代 estimateRigidTransform
    mtcnn
    pytorch 指定GPU
    cv2.imread()与PIL中Image.open(),以及相互转换
  • 原文地址:https://www.cnblogs.com/smart-girl/p/10007339.html
Copyright © 2011-2022 走看看