将React Hooks组件转换为Class类组件后出现报错该如何解决?
问题修复方案
错误原因
你的报错和createRef/useRef的差异无关,核心是构造函数中定义refValt的方式错误:
你在constructor里用const refValt = React.createRef(null)声明的是构造函数内部的局部变量,没有挂载到类实例的this上,后续调用this.refValt自然是undefined,才会触发无法读取属性的报错。
另外有个逻辑对齐优化点:你当前把myfuncValt定义在类外部属于全局函数,最好放到类内部作为实例方法,和原Hooks组件的作用域逻辑保持一致。
修复后的完整代码
import React from "react"; class App extends React.Component { constructor(props) { super(props); // 把ref挂载到类实例this上,后续才能通过this.refValt访问 this.refValt = React.createRef(null); // 绑定方法的this指向,若用箭头函数定义方法可省略该步骤 this.myfuncValt = this.myfuncValt.bind(this); } myfuncValt() { console.log("222222222222222222222"); } componentDidMount() { setTimeout(() => { // createRef和useRef用法一致,都需要通过.current访问挂载的DOM节点 this.refValt.current.click(); }, 5000); } render() { return ( <div> <div ref={this.refValt} onClick={this.myfuncValt}> Valt </div> </div> ); } } export default App;
补充说明
如果不想在constructor里绑定方法的this,也可以直接用类属性箭头函数定义myfuncValt:
// 直接在类内部定义,不需要额外做this绑定 myfuncValt = () => { console.log("222222222222222222222"); }
内容的提问来源于stack exchange,提问作者Tolga Kurtuluş
相关产品推荐
相关产品推荐

