如何将React Native Elements SearchBar的Cancel文本替换为自定义图标
解决方案
为什么修改defaultProps不生效
官方SearchBar的Cancel按钮在渲染逻辑里硬编码了使用<Text>组件展示cancelButtonTitle属性,就算你修改defaultProps里的文本内容,也只会改变显示的文字,无法渲染图标,必须修改渲染逻辑才能实现需求。
方案1:自定义封装(推荐,无需修改官方源码)
不需要改动react-native-elements的源码,只需要在业务代码里封装一层即可,避免后续升级组件库导致修改丢失:
import { View, StyleSheet } from 'react-native'; import { SearchBar, Icon } from 'react-native-elements'; // 如果你用了全局theme可以自行替换下面的theme取值逻辑 const CustomSearchBar = (props) => { return ( <View style={styles.searchContainer}> <SearchBar {...props} showCancel={false} // 关闭官方自带的取消按钮 containerStyle={styles.searchInnerContainer} /> {/* 自定义的图标取消按钮 */} <Icon type="material" size={25} color="#9e9e9e" name="arrow-back" onPress={props.onCancel} containerStyle={styles.cancelIconContainer} /> </View> ) } const styles = StyleSheet.create({ searchContainer: { flexDirection: 'row', alignItems: 'center', backgroundColor: '#fff', }, searchInnerContainer: { flex: 1, paddingHorizontal: 0, }, cancelIconContainer: { paddingHorizontal: 10, } }) export default CustomSearchBar;
后续业务里直接使用这个CustomSearchBar组件即可。
方案2:修改官方源码
如果一定要修改官方源码实现,可以按以下步骤操作,建议搭配patch-package使用避免修改丢失:
- 打开项目路径下的
node_modules/react-native-elements/src/searchbar/SearchBar.tsx(不同版本路径可能略有差异,找对应SearchBar的源码文件) - 修改props解构部分,新增
cancelIcon属性:
// 在原有props解构的参数里新增cancelIcon即可 const { theme, cancelButtonProps, cancelButtonTitle, cancelIcon, clearIcon, ...rest } = this.props;
- 修改defaultProps,新增默认cancelIcon配置:
SearchBar.defaultProps = { // 其他原有配置保持不变,新增下面的配置 cancelIcon: { type: 'material', size: 25, name: 'arrow-back', } }
- 替换Cancel按钮的Text渲染逻辑为Icon渲染:
找到原来的Cancel按钮部分的代码:
<View style={[buttonStyle, buttonDisabled && buttonDisabledStyle]}> <Text style={[ styles.buttonTextStyle, buttonColor && { color: buttonColor }, buttonTextStyle, buttonDisabled && (buttonDisabledTextStyle || styles.buttonTextDisabled), ]}> {cancelButtonTitle} </Text> </View>
替换为:
<View style={[buttonStyle, buttonDisabled && buttonDisabledStyle]}> {/* 这里用官方自带的renderNode方法渲染图标,和searchIcon、clearIcon逻辑一致 */} {renderNode(Icon, cancelIcon, defaultCancelIcon(theme))} </View>
同时把你准备的defaultCancelIcon方法复制到该文件顶部即可。
- (可选)使用patch-package持久化修改:
修改完成后执行以下命令生成补丁,后续重新安装依赖会自动应用修改:
npx patch-package react-native-elements
内容的提问来源于stack exchange,提问作者karste
相关产品推荐
相关产品推荐

