一、操作原生dom
三种方式
import React, { PureComponent, createRef } from 'react';// 编写一个组件 class App extends PureComponent {constructor() {super();this.state = {};this.titleRef2 = createRef();this.titleRef3 = createRef();}handleConsole = par => {// 方式一console.log(this.refs.m1);// 方式二console.log(this.titleRef2.current);// 方式三console.log(this.titleRef3.current);};render() {return (<div><h1 ref="m1">方式一</h1><h1 ref={this.titleRef2}>方式二</h1><h1 ref={e => (this.titleRef3.current = e)}>方式三</h1><button onClick={e => this.handleConsole()}>点击</button></div> );} }export default App;
二、操作组件
1.类组件
和获取原生dom的方式二一样,先通过createRef()得到一个变量,然后绑定上去即可。
2.函数组件
也要先通过createRef()得到一个变量,但是子组件函数要用forwardRef包裹起来。然后把ref放到函数返回的元素的上面。
import React, { PureComponent, createRef ,forwardRef } from 'react';const Footer = forwardRef((props,ref)=>{return <h3 ref={ref}>Footer child component</h3> })class Body extends PureComponent {test(){console.log(111);}render() {return <h3>body child component</h3> } }// 编写一个组件 class App extends PureComponent {constructor() {super();this.state = {};this.titleRef = createRef();this.titleRef2 = createRef();}handleConsole = par => {// 获取类组件的ref实例console.log(this.titleRef.current);this.titleRef.current.test(); // 调用类组件的方法// 方式二console.log(this.titleRef2.current);};render() {return (<div><Body ref={this.titleRef}></Body><Footer ref={this.titleRef2}></Footer><button onClick={e => this.handleConsole()}>点击</button></div> );} }export default App;