React Native onLayout获取height报错:NSString无法转为ABI46_0_0YGValue
React Native报错:JSON value of type NSString cannot be converted to a ABI46_0_0YGValue 原因及解决办法
报错原因
- 你给
height的初始状态设成了空字符串'',React Native底层的Yoga布局引擎要求bottom这类布局属性必须是数值类型,字符串值无法被解析,直接抛出类型转换错误。 - 虽然
onLayout回调会在红色视图渲染后把height更新为数值,但组件第一次渲染时,蓝色视图的bottom属性已经用了初始的空字符串值,触发了报错。
解决办法
把height的初始状态从空字符串改成数值类型(比如0),初始值设为0不会影响后续布局,onLayout触发后会自动更新为红色视图的实际高度。
修改后的完整代码:
import { Text, View} from 'react-native'; import {useState} from 'react' export default function App() { // 将初始值从''改为0 const [height, setHeight] = useState(0) return ( <View style={{ backgroundColor: 'green', flex: 1 }}> <View style={{ backgroundColor: 'blue', position: 'absolute', left: 0, right: 0, top: 0, bottom: height, }}> </View> <View onLayout={({ nativeEvent }) => { const { x, y, width, height } = nativeEvent.layout setHeight(height) }} style={{ backgroundColor: 'red', position: 'absolute', left: 0, right: 0, bottom: 0, padding: 20 }}> <Text>Lorem Ipsum</Text> </View> </View> ); }
内容的提问来源于stack exchange,提问作者Assat
相关产品推荐
相关产品推荐

