React中ref的使用

作者: SuperBinlin | 来源:发表于2017-06-15 18:07 被阅读3405次

    在react中,一般情况下,数据通过props来交互,但是在某些情况下,仍需用到ref,在官网中是这样说的

    In the typical React dataflow, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props. However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow. The child to be modified could be an instance of a React component, or it could be a DOM element. For both of these cases, React provides an escape hatch.

    ref有两种使用方式

    1.设置回调函数(官方推荐)
    2.设置string

    我们以实现input获取焦点为例,探索这俩种方式的使用方式

    回调函数方式

    class Demo extends React.Component{
      constructor(props) {
        super(props);
        this.state = {           
          isInputshow:false                       //控制input是否渲染
        }
      }
    
      inputRefcb(instance){
        if(instance) {                            //确保不为null
          instance.focus();                     
        }
      }
    
      render() {
       {
          this.state.isInputshow ? 
          <div>
            <input ref={this.inputRefcb} type="text" />
          </div>
          : null           
        }
      }
    }
    

    该回调有三种触发时机

    • 组件被渲染后 回调参数instance 为input的dom对象
    • 组件被卸载后 回调参数instance 为null,确保内存不被泄露
    • ref改变后

    string方式

    class Demo extends React.Component{
      constructor(props) {
        super(props);
    
        onFocus(){
         this.refs.inputRef.focus()
        }
      }
      render() {
        <div>
          <input ref="inputRef" type="text" />
        </div>
        <input type="button" value="Focus" onClick={this.onFocus} />
      }
    }
    

    通过this.refs.inputRef获取组件实例,并触发focus()方法

    最后再引用官方的一句话:)

    Don't Overuse Refs

    相关文章

      网友评论

        本文标题:React中ref的使用

        本文链接:https://www.haomeiwen.com/subject/ntkuqxtx.html