问题:Taro.createSelectorQuery()在 useEffect 里 一直找不到元素
代码记录附上:
scss
useEffect(() => {
const query = Taro.createSelectorQuery();
query.select('#some-element').boundingClientRect((rect) => {
console.log(rect); // ❌ always null
}).exec();
}, []);
查阅链接后 docs.taro.zone/en/docs/ref 发现,考虑到小程序的实现机制,需要配合在 onReady 生命周期中获取节点信息。也就是Taro.createSelectorQuery要放在 onReady阶段,ai回答的这段话是错误的,react hook和小程序钩子没有一一对应的关系。

修改后代码
js
// a 元素滑动到b 元素
useReady(() => {
Taro.createIntersectionObserver(
Taro.getCurrentInstance(),
{
thresholds: [0.2],
observeAll: true,
},
).relativeTo('#b', { bottom: -400 }).observe('#a', (res) => {
// do someting...
console.log(res)
});
});