// 类名使用 PascalCase,描述类的用途
class YourClass {
constructor(param1, param2) {
// 初始化属性
this.property1 = []
this.property2 = param1
this.property3 = param2
// 立即执行初始化逻辑
this.init()
}
async init() {
// 异步初始化逻辑
// 例如:读取数据、调用 API 等
}
async method1() {
// 通过 this. 访问属性
this.property1.push(item)
}
async method2() {
// 调用其他方法
await this.method1()
}
}
// 导出类
export { YourClass }
import { YourClass } from './your-class.js'
function YourComponent({ show }) {
const yourRef = useRef(null)
useEffect(() => {
// 创建实例,生命周期与组件一致
yourRef.current = new YourClass(param1, param2)
// 页面销毁时清理
return () => {
yourRef.current = null
}
}, [])
return (
<div onClick={() => yourRef.current?.method1()}>
{/* UI */}
</div>
)
}
init() 方法this.property 访问属性?. 避免空引用错误参考 src/page/device/device.js 和 src/page/device/device.jsx