1
This commit is contained in:
@@ -27,13 +27,31 @@ export const useKeyboardStore = create<KeyboardStore>((set, get) => ({
|
||||
setKeyboardHeight: (height: number) => {
|
||||
set({ keyboardHeight: height })
|
||||
const { listeners } = get()
|
||||
listeners.forEach(listener => listener(height, get().isKeyboardVisible))
|
||||
// 使用 requestAnimationFrame 异步执行监听器,避免阻塞主线程
|
||||
requestAnimationFrame(() => {
|
||||
listeners.forEach(listener => {
|
||||
try {
|
||||
listener(height, get().isKeyboardVisible)
|
||||
} catch (error) {
|
||||
console.error('键盘监听器执行错误:', error)
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
setKeyboardVisible: (visible: boolean) => {
|
||||
set({ isKeyboardVisible: visible })
|
||||
const { listeners } = get()
|
||||
listeners.forEach(listener => listener(get().keyboardHeight, visible))
|
||||
// 使用 requestAnimationFrame 异步执行监听器,避免阻塞主线程
|
||||
requestAnimationFrame(() => {
|
||||
listeners.forEach(listener => {
|
||||
try {
|
||||
listener(get().keyboardHeight, visible)
|
||||
} catch (error) {
|
||||
console.error('键盘监听器执行错误:', error)
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
|
||||
addListener: (listener: (height: number, visible: boolean) => void) => {
|
||||
@@ -52,18 +70,36 @@ export const useKeyboardStore = create<KeyboardStore>((set, get) => ({
|
||||
|
||||
console.log('初始化全局键盘监听器')
|
||||
|
||||
// 使用防抖优化,避免频繁触发
|
||||
let lastHeight = 0
|
||||
let lastTime = 0
|
||||
const debounceDelay = 16 // 约一帧的时间
|
||||
|
||||
Taro.onKeyboardHeightChange?.((res: any) => {
|
||||
const height = Number(res?.height || 0)
|
||||
const now = Date.now()
|
||||
|
||||
// 防抖:如果高度没变化或时间间隔太短,忽略
|
||||
if (height === lastHeight && (now - lastTime) < debounceDelay) {
|
||||
return
|
||||
}
|
||||
|
||||
lastHeight = height
|
||||
lastTime = now
|
||||
|
||||
console.log('全局键盘高度变化:', height)
|
||||
|
||||
const store = get()
|
||||
if (height > 0) {
|
||||
store.setKeyboardVisible(true)
|
||||
store.setKeyboardHeight(height)
|
||||
} else {
|
||||
store.setKeyboardVisible(false)
|
||||
store.setKeyboardHeight(0)
|
||||
}
|
||||
// 使用 requestAnimationFrame 延迟执行,避免阻塞消息处理
|
||||
requestAnimationFrame(() => {
|
||||
const store = get()
|
||||
if (height > 0) {
|
||||
store.setKeyboardVisible(true)
|
||||
store.setKeyboardHeight(height)
|
||||
} else {
|
||||
store.setKeyboardVisible(false)
|
||||
store.setKeyboardHeight(0)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
set({ isInitialized: true })
|
||||
|
||||
Reference in New Issue
Block a user