React获取DOM方法

以下提供三种方法:

1. js 常规dom操作方式,通过id获取dom

2.react原生函数findDOMNode获取dom

3.通过ref来定位一个组件,切记ref要全局唯一(类似id)

  1. import React, { Component } from 'react';
  2. import ReactDOM from 'react-dom';
  3. class Index extends Component {
  4. onClick(event){
  5. console.log(event.target.value);
  6. // 第一种方式
  7. var submitObj = document.getElementById( 'submit');
  8. submitObj.style.color = 'green';
  9. // 第二种方式
  10. ReactDOM.findDOMNode(submitObj).style.color = 'yellow';
  11. // 第三种方式
  12. this.refs.submit.style.color = 'blue';
  13. }
  14. render(){
  15. return (
  16. <div>
  17. <input id='submit' ref='submit'
  18. type= 'button' value= 'style'
  19. onClick= {this.onClick.bind(this)}/>
  20. </div>
  21. )
  22. }
  23. }
  24. ReactDOM.render( <Index/>,document.getElementById('container'));

猜你喜欢

转载自blog.csdn.net/cloveryuan/article/details/80967424