使用NeomorphFlex(react-native-neomorph-shadows)时出现match属性读取错误
问题解决:react-native-neomorph-shadows NeomorphFlex 样式数组导致 "cannot read property 'match' of undefined" 错误
问题背景
使用NeomorphFlex组件时,需要合并全局默认样式、动态自定义样式和传入的props.style,因此将样式以数组形式传入,但触发了Error cannot read property 'match' of undefined错误,且无法直接移除样式数组。
解决方案
该库的Neomorph系列组件不支持直接接收样式数组作为style属性,仅接受单一的样式对象。可以通过StyleSheet.flatten()方法将多个样式(对象/数组形式)合并为单个样式对象,同时处理可能的undefined样式项:
修改后的代码
import { StyleSheet } from 'react-native'; // ... 其他代码 // 合并所有样式为单一对象 const styleuse = StyleSheet.flatten([ globalStyles.buttonContained, { backgroundColor: useColor, padding: usePadding, width: fillContent ? undefined : "100%", shadowRadius: 5 }, // 处理props.style可能为undefined的情况 style || {}, ]) as ViewStyle; return ( <Pressable onPress={disabled ? undefined : onPress} {...props} > <NeomorphFlex swapShadows // 传入合并后的单一样式对象 style={styleuse} > {prefixIcon ? ( <IconStyled icon={prefixIcon} color={props.prefixIconColor ? props.prefixIconColor : "primary"} /> ) : null} <View style={{ flexShrink: 1 }}>{children}</View> {suffixIcon ? ( <IconStyled icon={suffixIcon} color={props.suffixIconColor ? props.suffixIconColor : "primary"} /> ) : null} </NeomorphFlex> </Pressable> );
原理说明
StyleSheet.flatten()是React Native内置方法,能够将嵌套的样式数组、多个样式对象合并为一个单一的样式对象,完全保留所有样式规则的优先级(后传入的样式会覆盖先传入的同名规则)。- 加入
style || {}是为了避免当props.style为undefined时,数组中出现无效项导致的合并异常。
内容的提问来源于stack exchange,提问作者Gabi Mangili
相关产品推荐
相关产品推荐

