React获取DOM方法

xiaoxiao2021-02-28  79

以下提供三种方法:

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

2.react原生函数findDOMNode获取dom

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

import React, { Component } from 'react'; import ReactDOM from 'react-dom'; class Index extends Component { onClick(event){ console.log(event.target.value); // 第一种方式 var submitObj = document.getElementById('submit'); submitObj.style.color = 'green'; // 第二种方式 ReactDOM.findDOMNode(submitObj).style.color = 'yellow'; // 第三种方式 this.refs.submit.style.color = 'blue'; } render(){ return ( <div> <input id='submit' ref='submit' type='button' value='style' onClick={this.onClick.bind(this)}/> </div> ) } } ReactDOM.render(<Index/>,document.getElementById('container'));

转载请注明原文地址: https://www.6miu.com/read-44189.html

最新回复(0)