React Native使用react-native-qrcode-scanner如何在相机扫码标记下方添加文字
二维码扫描视图添加扫码提示文字解决方案
问题原因
你设置position: absolute后文字不显示有两个核心原因:
- 若你将Text组件直接放在
QRCodeScanner组件内部作为子元素,该组件内部布局逻辑会忽略自定义子元素,不会渲染在视图层 - 未设置足够高的
zIndex,文字层级低于相机视图,被相机层覆盖不可见
解决方案1:使用customMarker自定义扫码标记(更推荐)
该方案无需手动计算位置,提示文字默认跟随扫码框居中,可自动适配所有尺寸设备。你只需要把原有showMarker属性替换为customMarker自定义标记即可,完整代码如下:
import { View, Text, StyleSheet, Dimensions } from 'react-native'; import QRCodeScanner from 'react-native-qrcode-scanner'; return ( <QRCodeScanner onRead={onSuccess} reactivate={true} // 替换原有showMarker属性 customMarker={ <View style={styles.markerWrapper}> <View style={styles.marker} /> <Text style={styles.scanTip}>将二维码放入框内,即可自动扫描</Text> </View> } containerStyle={styles.cameraContainer} cameraStyle={{ ...styles.camera, height: Dimensions.get('window').height - topOffset, }} topViewStyle={styles.topView} bottomViewStyle={styles.bottomView} cameraProps={{ type: 'back', }} /> ); const styles = StyleSheet.create({ cameraContainer: { backgroundColor: theme.colors.background, }, camera: {}, bottomView: { height: 0, flex: 0, }, topView: { height: 0, flex: 0, }, // 扫码框样式可自行调整宽高 marker: { width: 220, height: 220, borderWidth: 2, borderRadius: 10, borderColor: theme.colors.white, }, // 新增标记容器样式 markerWrapper: { alignItems: 'center', justifyContent: 'center', }, // 新增提示文字样式 scanTip: { marginTop: 20, color: theme.colors.white, fontSize: 14, } });
解决方案2:外层包裹容器绝对定位
如果不想修改原有marker逻辑,可以使用外层套父容器的方式实现:
import { View, Text, StyleSheet, Dimensions } from 'react-native'; import QRCodeScanner from 'react-native-qrcode-scanner'; return ( // 外层新增父容器 <View style={styles.wrapper}> <QRCodeScanner onRead={onSuccess} reactivate={true} showMarker containerStyle={styles.cameraContainer} cameraStyle={{ ...styles.camera, height: Dimensions.get('window').height - topOffset, }} topViewStyle={styles.topView} markerStyle={styles.marker} bottomViewStyle={styles.bottomView} cameraProps={{ type: 'back', }} /> <Text style={styles.scanTip}>将二维码放入框内,即可自动扫描</Text> </View> ); const styles = StyleSheet.create({ cameraContainer: { backgroundColor: theme.colors.background, }, camera: {}, bottomView: { height: 0, flex: 0, }, topView: { height: 0, flex: 0, }, marker: { borderWidth: 2, borderRadius: 10, borderColor: theme.colors.white, }, // 新增父容器样式 wrapper: { flex: 1, position: 'relative', }, // 新增提示文字样式 scanTip: { position: 'absolute', zIndex: 100, // 必须设置,保证文字层级高于相机视图 width: '100%', textAlign: 'center', top: '50%', // 可根据扫码框实际高度调整marginTop,数值为扫码框高度的一半+你需要的间距 marginTop: 130, color: theme.colors.white, fontSize: 14, } });
内容的提问来源于stack exchange,提问作者Dmitriy Bucaev
相关产品推荐
相关产品推荐

