如何修复React Native中‘Transform with key of translateY must be a number’错误?
React Native中transform百分比报错的解决办法
问题出在React Native的transform属性规则上:translateY不支持直接传入字符串格式的百分比(比如"-50%"),必须使用数字类型的值,或者通过Animated的插值逻辑实现百分比偏移。
给你两种可行的解决方式:
方式一:基于元素固定高度计算偏移
既然你的图片高度是固定24,直接计算出一半高度作为偏移值,简单直接:
import { Animated, Image, View } from "react-native"; <Animated.View style={{ position: "absolute", right: 20, top: "50%", transform: [{ translateY: -12 }], // 24/2 = 12,取负数实现向上偏移 }} > {captchaImage && ( <Image source={{ uri: captchaImage }} style={{ width: 50, height: 24, resizeMode: "contain", }} /> )} </Animated.View>
方式二:用Animated插值实现百分比偏移
如果需要适配动态高度的元素,可以借助Animated的interpolate方法将百分比转换为数值:
import { Animated, Image, View } from "react-native"; // 初始化一个Animated值,这里用0作为初始值即可 const translateY = new Animated.Value(0); // 通过插值将百分比转换为相对自身高度的偏移 const interpolatedTranslateY = translateY.interpolate({ inputRange: [0, 1], outputRange: ["-50%", "-50%"], // Animated会自动处理百分比到数值的转换 }); <Animated.View style={{ position: "absolute", right: 20, top: "50%", transform: [{ translateY: interpolatedTranslateY }], }} > {captchaImage && ( <Image source={{ uri: captchaImage }} style={{ width: 50, height: 24, resizeMode: "contain", }} /> )} </Animated.View>
另外补充一种不用transform的思路:利用flex布局直接居中,代码更简洁:
<Animated.View style={{ position: "absolute", right: 20, top: 0, bottom: 0, justifyContent: "center", // 借助flex垂直居中 }} > {captchaImage && ( <Image source={{ uri: captchaImage }} style={{ width: 50, height: 24, resizeMode: "contain", }} /> )} </Animated.View>
内容的提问来源于stack exchange,提问作者sinan
相关产品推荐
相关产品推荐

