React Native集成Stripe CardForm遇Binary XML错误求助
问题:React Native集成Stripe CardForm组件时出现XML布局错误
在React Native中集成Stripe的CardForm组件,已按要求添加Material Components依赖,但运行时出现错误:Binary XML file line #9 in com.client:layout/stripe_card_form_view
现有配置
android/app/build.gradle 依赖
dependencies { implementation 'androidx.appcompat:appcompat:1.4.1' implementation 'com.google.android.material:material:1.6.0' }
package.json 依赖
"dependencies": { "@stripe/stripe-react-native": "^0.22.0" }
组件代码
import { StyleSheet, Text, View, Modal } from 'react-native'; import React from 'react'; import { StripeProvider, usePaymentSheet, CardField, CardForm, useStripe, } from '@stripe/stripe-react-native'; const PaymentModal = () => { function PaymentScreen() { return ( <View> <CardForm postalCodeEnabled={true} cardStyle={{ backgroundColor: '#FFFFFF', textColor: '#000000', borderWidth: 1, }} style={{ width: '100%', height: 50, marginVertical: 30, }} onCardChange={cardDetails => { setCard(cardDetails); }} onFocus={focusedField => { console.log('focusField', focusedField); }} /> </View> ); } return ( <Modal visible={true} transparent={true} animationType="slide" onRequestClose={() => null}> <View style={{ backgroundColor: 'rgba(0, 0, 0, 0.5)', flex: 1, alignItems: "center", justifyContent: "flex-end" }}> <View style={{ width: "100%", height: "60%", backgroundColor: "white" }}> <StripeProvider publishableKey="pk_test_51MBYAwFjaRQnIgRgw0j5Qo40oXqM5UijDDo5L6ynKB68VZJ3KLJN0b90b9HNpJ90c4CJqe7BHR2kvKSQOW45Z2yb00A0I2UpnH"> <PaymentScreen /> {/* <Button title='Buy' onPress={buy} /> */} </StripeProvider> </View> </View> </Modal> ); } export default PaymentModal const styles = StyleSheet.create({})
解决方案
1. 确保App主题继承Material Components主题
Stripe CardForm依赖Material Components主题,需修改android/app/src/main/res/values/styles.xml(及对应深色主题文件),将App主题改为继承Material Components主题:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style>
深色主题可替换为Theme.MaterialComponents.Dark.NoActionBar。
2. 升级Stripe React Native版本
当前使用的0.22.0版本较旧,可能与Material Components 1.6.0存在兼容性问题,升级到最新稳定版:
npm install @stripe/stripe-react-native@latest # 或使用yarn yarn add @stripe/stripe-react-native@latest
升级后执行pod install(iOS)或./gradlew clean(Android)清理缓存。
3. 修复代码未定义变量
组件中onCardChange里的setCard函数未定义,需添加状态声明:
const PaymentModal = () => { const [card, setCard] = React.useState(null); // 新增状态定义 function PaymentScreen() { // 原有代码保持不变 } // 原有代码保持不变 }
4. 清理并重新构建项目
- Android端:
cd android && ./gradlew clean && cd .. && npx react-native run-android
- iOS端:
cd ios && pod deintegrate && pod install && cd .. && npx react-native run-ios
内容的提问来源于stack exchange,提问作者Almighty Dee
相关产品推荐
相关产品推荐

