react获取真实DOM节点:

下面是几个适合使用 refs 的情况:

管理焦点,文本选择或媒体播放。---操作DOM

触发强制动画。

集成第三方 DOM 库。

1. this.refs 字符串—已废弃—依然可以用

2. React.createRef() 推荐使用-React16.3

import React, { Component } from 'react'

export default class App extends Component {

  constructor(){

    super();

    this.myInput=React.createRef();

  }

  handdleClick=()=>{

    console.dir(this.myInput.current);

    this.myInput.current.focus();

  }

  render() {

    return (

      <div>

        <input type="text" ref={this.myInput} />

        点击让文本框获得焦点

      </div>

    )

  }

}

3. 回调函数 ref={回调函数}

import React from 'react'

//孙子

function GrandCihld(props) {

  return (

      <div>

);

}

//儿子

function Child(props) {

return (

  <div> My input: <GrandCihld inputRef={props.inputRef} /></div>

);

}

//父亲

class App extends React.Component {

  handdleClick=()=>{

    console.log("this.inputElement",this.inputElement);

    this.inputElement.focus();

  }

render() {

  return (

    <div>

      <Child inputRef={el => {

                this.inputElement = el;

                console.log("匿名函数被调用了");

              }} />

      点击获取焦点

    </div>

  );

}

}

export default App;

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容