ref的作用
一句话总结:获取真实DOM
Refs 是 React 中引用(references)的简写。可以用于获取一个 DOM 节点或者 React 组件的引用。它是一个有助于存储对特定的 React 元素或组件的引用的属性,它将由组件渲染配置函数返回。可以用来绑定到 render() 输出的任何组件上。
createRef()获取DOM节点引用
①在constructor中this.name = React.createRef();
②在元素上绑定ref = { this.name }
③获取ref值:this.name.current.value
constructor(){super();this.name = React.createRef();
}
render() {return (<div><input type="text" name="name" ref={this.name}/><button onClick={()=>{console.log(this.name.current.value)}}>获取DOM节点的引用</button></div>)
}
createRef()获取组件引用
假如我们在父组件中引入一个输入框子组件,要获取这个输入框的值,如何做呢?
①将子组件作为普通DOM元素,在父组件中引入子组件,并为子组件添加ref,ref = { this.input }
②如果在父组件中调用this.input.current,就可以获取子组件的信息
③在子组件中定义函数getInputValue,用于输出输入框的值,再在父组件中调用this.input.current.getInputValue(),就可以获取输入框的值
// 父组件
export default class RefComponent extends Component {constructor(){super();this.input = React.createRef()}render() {return (<div><InputComponent ref={this.input}></InputComponent><button onClick={()=>{console.log(this.input.current)console.log(this.input.current.getName())}}>获取组件中的ref值</button></div>)}
}// 子组件
class InputComponent extends Component {constructor(){super();this.name = React.createRef()}getName(){return this.name.current.value;}render() {return (<div><input type="text"ref={this.name}/></div>)}
}
回调函数获取DOM节点引用
①在constructor中this.name = null;
②定义回调函数
getNameRef = (e) => { this.name = e; }
③在元素上绑定ref = { this.getNameRef }
④获取ref值:this.name.value