react动态获取ref
动态ref示例
import React from "react"; class MyComponent extends React.Component { myRef: React.RefObject<unknown>; private _refMaps: Map<any, any>; constructor(props: {}) { super(props); this.myRef = React.createRef(); this._refMaps = new Map(); } componentDidMount() { console.log(this.myRef.current); // 访问DOM元素 console.log(this.getRef("myRef").current); // 访问自定义引用 } getRef(key: any) { if (!this._refMaps.has(key)) { this._refMaps.set(key, React.createRef()); } return this._refMaps.get(key); } render() { return ( <> <div ref={this.myRef}>Hello, world!</div> <div ref={this.getRef("myRef")}>Hello, world!</div> </> ); } } export default MyComponent;
其他资料: ES6的Map函数详解