簡體   English   中英

如何在 react-native 中正確鍵入 measureLayout

[英]How to properly type measureLayout in react-native

我需要設置 SVG 的高度,以便它只占用下面表格允許的空間,以便所有元素都適合視口。 為此,根據文檔,我已將 ref 轉發到表單組件並使用 measureLayout function 計算了它應該采用的尺寸

measureLayout(relativeToNativeComponentRef, onSuccess, onFail) 類似於 measure(),但測量相對於祖先的視圖,由 relativeToNativeComponentRef 引用指定。 這意味着返回的坐標是相對於祖先視圖的原點 x、y 的。

示例表明,他們只是將兩個 ref 附加到父級和一個子級,起始值為 null 並且它可以工作。

在 typescript 中,第一個參數 - relativeToNativeComponentRef 的類型為 RefObject<number | HostComponent> 並且元素上的 ref 應該是 LegacyRef | 未定義,雖然代碼有效,但我不知道如何正確輸入它,而且在初始加載時,所有值都是 0 0 0 0,只有當我手動刷新它才能正確顯示,你能提示我嗎? 代碼是

const { height: viewportHeight } = Dimensions.get("window");

export const Home: React.FC<HomeScreenProps> = ({ navigation }) => {
  const [svgHeight, setSvgHeight] = useState(0);
  const svgHeightForwardedRef = useRef<View | null>(null);
  const dispatch = useAppDispatch();
  const onSumbit = (data: UserMetrics) => {
    const { gender, age } = data;
    dispatch(setUserData(data));
    navigation.navigate("Tests", { gender, age });
  };

  const homeScreenContainerRef = useRef<number | HostComponent<unknown>>(null);

  useLayoutEffect(() => {
    if (svgHeightForwardedRef.current && homeScreenContainerRef.current) {
      svgHeightForwardedRef.current?.measureLayout(
        homeScreenContainerRef.current,
        (left, top, width, height) => {
          console.log(left, top, width, height);
          const svgHeightPerPlatform =
            Platform.OS === "web"
              ? viewportHeight - height + top
              : viewportHeight - height - top;
          setSvgHeight(svgHeightPerPlatform);
        },
        () => {
          console.log("fail");
        }
      );
    }
  }, [svgHeightForwardedRef, homeScreenContainerRef]);
  return (
    <View style={styles.container} ref={homeScreenContainerRef}>
      <View style={styles.wrapper}>
        <StatusBar style="auto" />
        <Text style={styles.welcomeText}>Test Reminder</Text>
        <View style={styles.heroWrapper}>
          <HeroSVG
            width={PLATFORM_WIDTH}
            height={svgHeight}
            preserveAspectRatio="xMidYMid meet"
          />
        </View>
        <HealthCheckForm onSubmit={onSumbit} ref={svgHeightForwardedRef} />
      </View>
    </View>
  );
};

非常感謝

編輯:我已經解決了“並且在初始加載時,所有值都是 0 0 0 0,只有當我手動刷新它才能正確顯示,你能提示我嗎?”通過放置 [svgHeightForwardedRef.current, homeScreenContainerRef.current]在依賴數組而不是 [svgHeightForwardedRef, homeScreenContainerRef] 中,我仍然需要 typescript 的幫助,謝謝。

使用findNodeHandle轉換 ref 的類型

import {findNodeHandle, StyleSheet, Text, View} from 'react-native';

export const Home: React.FC<any> = ({}) => {
  const textContainerRef = useRef<View>(null);
  const textRef = useRef<Text>(null);
  const [measure, setMeasure] = useState<{
    left: number;
    top: number;
    width: number;
    height: number;
  } | null>(null);

  useEffect(() => {
    const textRefHandle = findNodeHandle(textContainerRef.current);
    if (textRef.current && textRefHandle) {
      textRef.current.measureLayout(
        textRefHandle,
        (left, top, width, height) => {
          setMeasure({left, top, width, height});
        },
        () => console.log('fail'),
      );
    }
  }, [measure]);

  return (
    <View style={styles.container}>
      <View ref={textContainerRef} style={styles.textContainer}>
        <Text ref={textRef}>Where am I? (relative to the text container)</Text>
      </View>
      <Text style={styles.measure}>{JSON.stringify(measure)}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  textContainer: {
    backgroundColor: '#61dafb',
    justifyContent: 'center',
    alignItems: 'center',
    padding: 12,
  },
  measure: {
    textAlign: 'center',
    padding: 12,
  },
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM