React 获取原生DOM元素/组件
react dom ref
获取原生 DOM 元素
import React, { PureComponent, createRef } from "react";
export class RefDemo extends PureComponent {
constructor(props) {
super(props);
this.state = {};
this.title2Ref = createRef();
this.title3Ref = null;
}
showTitle1Ref() {
console.log(this.refs.title1);
}
showTitle2Ref() {
console.log(this.title2Ref.current);
}
showTitle3Ref() {
console.log(this.title3Ref);
}
render() {
return (
<div>
{/* 1 通过refs获取 将被弃用 */}
<h2 ref="title1">Title1</h2>
<button onClick={(e) => this.showTitle1Ref()}>showTitle1Ref</button>
{/* 2 通过createRef方法, 获取current 推荐该方法*/}
<h2 ref={this.title2Ref}>Title2</h2>
<button onClick={(e) => this.showTitle2Ref()}>showTitle2Ref</button>
{/* 3.通过传入一个回调方法 在元素被渲染后执行,在方法内赋值*/}
<h2 ref={(el) => (this.title3Ref = el)}>Title3</h2>
<button onClick={(e) => this.showTitle3Ref()}>showTitle3Ref</button>
</div>
);
}
}
export default RefDemo;
获取组件实例/函数组件内部 DOM
import React, { memo, PureComponent, createRef, forwardRef } from "react";
const FunctionComponent = forwardRef((props, ref) => {
return (
<div ref={ref}>
<span>FunctionComponent</span>
</div>
);
});
class ClassComponent extends PureComponent {
showMsg() {
console.log("classComponentClick");
}
render() {
return (
<div>
<span>ClassComponent</span>
</div>
);
}
}
const GetComponent = memo(() => {
const classRef = createRef();
const componentRef = createRef();
function clickClassComponent() {
console.log(classRef.current);
classRef.current.showMsg();
}
function clickFunctionComponent() {
console.log(componentRef.current);
}
return (
<div>
{/* 类组件可以通过ref直接获取到组件实例,也可以调用组件实例上的方法 */}
<ClassComponent ref={classRef}></ClassComponent>
<button onClick={(e) => clickClassComponent()}>
classComponentClick
</button>
{/* 函数式组件没有实例,只能通过ref获取到组件内的某个DOM元素,函数组件需要通过forwardRef包裹 */}
<FunctionComponent ref={componentRef}></FunctionComponent>
<button onClick={(e) => clickFunctionComponent()}>
functionComponentClick
</button>
</div>
);
});
export default GetComponent;