alibaba / rax

🐰 Rax is a progressive framework for building universal application. https://rax.js.org
Other
8k stars 627 forks source link

[Question]getBoundingClientRect 小程序下是空的 #2283

Closed waylon-gmail closed 2 years ago

waylon-gmail commented 2 years ago
const viewWidth = viewRef.current.getBoundingClientRect().width;

小程序下是空的, 有其他办法吗?做动画的时候为了计算滚动速度,需要取一下宽度。

ChrisCindy commented 2 years ago

https://rax.js.org/docs/guide/miniapp-faq#3.%20%E5%B0%8F%E7%A8%8B%E5%BA%8F%E5%8E%9F%E7%94%9F%E4%BD%9C%E7%94%A8%E5%9F%9F%E6%80%8E%E4%B9%88%E8%8E%B7%E5%8F%96%EF%BC%9F

waylon-gmail commented 2 years ago
        const element: any = document.getElementById('component-notice-container-cont');
        const nativeInstance = element._internal; // 获取小程序 Page 或 Component 实例
        const selectorQuery: any = nativeInstance.createSelectorQuery();
        selectorQuery.select('#component-notice-container-cont').boundingClientRect();
        selectorQuery.select('#component-notice-container-cont-text').boundingClientRect();
        selectorQuery.exec((res) => {
          console.log('res', res);
        });

      <View className="cont" id={'component-notice-container-cont'} ref={viewRef}>
        <Text className="text animation-text" id={'component-notice-container-cont-text'} ref={textRef}>{content}</Text>
      </View>

打印出来的res是 [null, null], 不知道问题出在哪。

waylon-gmail commented 2 years ago

在前面稍微delay 200毫秒,就取到了。 是取的时机不对吗?在什么方法回调中取才不需要延时呢。

useEffect(() => { move().then(); ---> 这里面的方法最前面 delay 200毫秒 }, [textRef.current]);

微信小程序延时一下可以取到,但是支付宝小程序直接就报错了。 image

waylon-gmail commented 2 years ago

上面那个微信小程序中稍微延时一下取到了(支付宝小程序报错),又遇到一个新的问题,这个动画怎么设置进去?

问题: document.styleSheets[0] ==> 不存在

  const addAnimation = (start, end, duration) => {
    const element: any = document.getElementById('component-notice-container-cont-text');
    element.style.animation = `notice_move_1 ${duration}s linear infinite;`;

    // 获取样式表引用
    const styleSheets: any = document.styleSheets[0];
    console.log('styleSheets', styleSheets);
    // 获取样式表中包含样式的个数
    const index = styleSheets.length;
    // 判断浏览器是否支持insertRule()方法
    if (styleSheets.insertRule) {
      styleSheets.insertRule(`@keyframes notice_move_1
            {
                from {
                    transform: translateX(${start}px);
                }
                to {
                    transform: translateX(${end}px);
                }
            }`, index);
    }
  };
SoloJiang commented 2 years ago

多端场景动画推荐使用这个 API https://rax.js.org/docs/api/createAnimation

小程序因为一些特殊的原因无法使用 @keyframes 的方式动态添加动画