解决react-native下背景图渲染,统一处理组件BackgroundImage
import {Image,ImageResizeMode,StyleProp,View,ViewStyle
} from 'react-native';function formatSrc(src: string) {if (!/^url\(.+?\)$/.test(src)) {return src;}return src.substring(4, src.length - 1);
}export interface BackgroundImageProps {/*** 图片地址,可以是 plaintext 或者 `url()` 的样式语法*/src?: string | null;/*** 作用于组件外层容器的样式** @defaults {}*/style?: object;/*** 图片缩放模式** 参考: https://reactnative.dev/docs/image#resizemode** @defaults 'cover'*/resizeMode?: ImageResizeMode;
}/*** 背景图样式的<Image>替代实现** @example** ```* <BackgroundImage src={'http://foo.bar'}></BackgroundImage>* ```*/
export function BackgroundImage(props: BackgroundImageProps) {const { src, style = {}, resizeMode = 'cover' } = props;if (!src) {return null;}const containerStyle: StyleProp<ViewStyle> = {position: 'absolute',top: 0,left: 0,right: 0,bottom: 0,...style};const contentProps = {style: {flex: 1,resizeMode},source: {uri: formatSrc(src)}};return (<View style={containerStyle}><Image {...contentProps} /></View>);
}
直接调用
<BackgroundImage src={'http://foo.bar'}></BackgroundImage>