创建类的流程.md 1.6 KB

创建类的流程

1. 在 JS 文件中创建类

// 类名使用 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 }

2. 在 JSX 文件中使用类

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>
  )
}

3. 关键要点

  • 构造函数:接收参数,初始化属性,调用 init() 方法
  • init() 方法:执行异步初始化逻辑,不需要单独调用
  • this. 访问:所有方法中通过 this.property 访问属性
  • 生命周期:实例在组件挂载时创建,卸载时销毁
  • 可选链:调用方法时使用 ?. 避免空引用错误

4. 示例:DeviceClass

参考 src/page/device/device.jssrc/page/device/device.jsx