一切从需求出发,一切向功能看齐。我们讨论一个东西的时候,首先要知道它是干什么? react中的ref的作用就是用于获取DOM的,简单的说,你想获取一个input框的值,在react中怎么做呢?这时候ref就是你的首选。 基本格式:
<input type='text' ref='input' />获取方式:
const node = this.refs.input; const text = node.value.trim() console.log(text);直接看demo:
import React,{Component} from 'react' import { render } from 'react-dom' class App extends Component { handleClick(){ const node = this.refs.input; const text = node.value.trim() console.log(text); node.value = '' } handleClick1(){ const node = this.refs.input; const text = node.value.trim() console.log(text); alert(text); } render(){ return ( <div> <input type='text' ref='input' /> <button onClick={(e) => { this.handleClick(); }}>clear</button> <button onClick={(e) => { this.handleClick1(); }}>alert</button> </div> ) } } render(<App />,document.getElementById('root'))效果图如下:
我的理解: ref是react中用于专门标记某个组件下的标签,这些被标记的标签都被存放在refs这个对象中,引用的时候通过this.refs.[‘name’]使用。