React类组件中使用Ref操作组件遇报错,求解决方案
解决类组件中访问ref时this指向错误的问题
核心原因
你遇到的报错是因为类组件中未正确绑定方法的this指向,导致调用insideTheRef时,this为undefined,自然无法访问this.componentRef。
解决办法
方法1:构造函数中绑定this
在类的constructor里,声明ref的同时绑定方法的this:
constructor(props) { super(props); this.componentRef = React.createRef(null); // 绑定方法的this到类实例 this.insideTheRef = this.insideTheRef.bind(this); } insideTheRef() { console.log("button clicked"); this.componentRef.current.focus(); console.log("the consoled reref", this.componentRef.current); }
方法2:用箭头函数定义类方法
箭头函数会自动继承外层的this指向(即类实例),直接修改方法定义:
// 直接用箭头函数定义方法 insideTheRef = () => { console.log("button clicked"); this.componentRef.current.focus(); console.log("the consoled reref", this.componentRef.current); }
方法3:调用方法时用箭头函数包裹
在触发方法的元素上,用箭头函数包裹调用,临时绑定this:
<button onClick={() => this.insideTheRef()}>触发方法</button>
注意:这种方式每次组件渲染都会创建新的箭头函数,若组件频繁渲染,建议用前两种方法。
额外注意:子组件需支持ref传递
如果ChartRendererCustomised是函数组件,默认无法接收ref,需要用React.forwardRef包裹子组件,将ref传递到内部可聚焦的DOM元素或类组件上:
const ChartRendererCustomised = React.forwardRef((props, ref) => { // 将ref绑定到内部需要聚焦的DOM元素,比如input、div(需设置tabIndex) return <div ref={ref} tabIndex="0" {...props}></div>; });
内容的提问来源于stack exchange,提问作者Ajmal Rahman
相关产品推荐
相关产品推荐

