ref属性获取DOM元素


原生方法获取DOM(不推荐)

import React from 'react';

class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1 id={'box'}>获取DOM元素</h1>
<button onClick={() => this.btnClick()}>按钮</button>
</div>
)
}
btnClick = () => {
let box = document.getElementById('box');
console.log(box);
}
}

export default App;
  • 不推荐直接使用原生方式获取DOM

使用  this.refs 获取DOM(不推荐)

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1 ref={'box'}>获取DOM元素</h1>
        <button onClick={() => this.btnClick()}>按钮</button>
      </div>
    )
  }
  btnClick = () => {
    let box = this.refs.box;
    console.log(box);
  }
}

export default App;
  • 不推荐,过时的方式获取 DOM 

使用React.createRef (推荐)

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.box = React.createRef();
  }
  render() {
    return (
      <div>
        <h1 ref={this.box}>获取DOM元素</h1>
        <button onClick={() => this.btnClick()}>按钮</button>
      </div>
    )
  }
  btnClick = () => {
    console.log(this.box.current);
  }
}

export default App;
  • 推荐
  • 使用  React.createRef() 创建一个对象,将该对象赋值给 DOM 元素的 ref 属性,该对象的  current 就是该 DOM 对象

通过回调函数方式获取DOM (推荐)

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.box = null
  }
  render() {
    return (
      <div>
        <h1 ref={(ele) => this.box = ele}>获取DOM元素</h1>
        <button onClick={() => this.btnClick()}>按钮</button>
      </div>
    )
  }
  btnClick = () => {
    console.log(this.box);
  }
}

export default App;
  • 推荐
  • 给  DOM  元素添加  ref 属性,取值是一个函数,函数的第一个参数就是当前DOM元素

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM