React Native自定义CustomButton组件如何隐藏图标(传useIcon=false显示问号)
根因
你当前的CustomButton组件未做显隐控制,无论useIcon传什么值,都会固定渲染Icon组件。大部分React Native图标库在接收到空值、非法图标名,或者未满足渲染条件时,会默认渲染问号作为占位符,这就是出现问题的原因。
最优解决方案:给Icon组件加条件渲染
直接在CustomButton组件内部做逻辑控制,只有useIcon为true的时候才渲染图标,不需要依赖Icon组件的内部逻辑,改完后的代码如下:
export interface Props { title: string; disabled?: boolean; buttonStyle?: ViewStyle | ViewStyle[]; textStyle?: TextStyle | TextStyle[]; onPress: any; // 可以把useIcon改成可选,默认值设为false,不需要图标时不用特意传 useIcon?: boolean; iconName?:string; iconSize?:number iconColor?:string; } const CustomButton = (props: Props) => { // 给useIcon设置默认值为false const { useIcon = false } = props; return ( <TouchableOpacity onPress={props.onPress} style={[ props.disabled ? { ...styles.buttonStyle, backgroundColor: 'grey' } : styles.buttonStyle, props.buttonStyle, ]} disabled={props.disabled}> {/* 只有useIcon为true的时候才渲染Icon组件 */} {useIcon && ( <Icon name={props.iconName} size={props.iconSize} color={props.iconColor} /> )} <Text style={[styles.textStyle, props.textStyle]}>{props.title}</Text> </TouchableOpacity> ); };
调用示例
不需要图标的按钮可以直接这么写,不用额外传图标相关参数:
<CustomButton title={'无图标按钮'} buttonStyle={{ marginTop: 20, alignSelf: 'center' }} disabled={!props.isValid} onPress={() => console.log('点击无图标按钮')} />
如果需要用图标,传useIcon={true}和对应图标参数即可,和你之前的写法完全兼容。
内容的提问来源于stack exchange,提问作者Himanshu
相关产品推荐
相关产品推荐

