背景
React Native 組件本身并不支持web開發(fā)中background-image
樣式屬性,而是采用背景圖片組件ImageBackground
來實(shí)現(xiàn)背景圖片的效果续膳。因?yàn)轫?xiàng)目開發(fā)需要鸽捻,在使用ImageBackground
過程要要實(shí)現(xiàn)背景圓角border-radius
蜻展,發(fā)現(xiàn)官方?jīng)]有提供ImageBackground
組件style
的文檔锥忿,并且發(fā)現(xiàn)直接傳遞給style
屬性的樣式并不作用于背景組件本身。好奇之下寸认,閱讀了下該組件的源碼签财,實(shí)現(xiàn)方式特別簡單,但是有一個(gè)屬性尤為重要:imageStyle
核心源碼
class ImageBackground extends React.Component<$FlowFixMeProps> {
setNativeProps(props: Object) { ... }
...
render() {
const {children, style, imageStyle, imageRef, ...props} = this.props;
return (
<View style={style} ref={this._captureRef}>
<Image
{...props}
style={[
StyleSheet.absoluteFill,
{
// Temporary Workaround:
// Current (imperfect yet) implementation of <Image> overwrites width and height styles
// (which is not quite correct), and these styles conflict with explicitly set styles
// of <ImageBackground> and with our internal layout model here.
// So, we have to proxy/reapply these styles explicitly for actual <Image> component.
// This workaround should be removed after implementing proper support of
// intrinsic content size of the <Image>.
width: style.width,
height: style.height,
},
imageStyle,
]}
ref={imageRef}
/>
{children}
</View>
);
}
}
先看結(jié)構(gòu)偏塞,
<View>
<Image></Image>
{children} // 這里的children可以是任意組件
</View>
ImageBackground
的實(shí)現(xiàn)方式:<View>
組件中包含一個(gè)<Image>
和任意其它組件唱蒸,稍微提煉下:
<View style={style} ref={this._captureRef}>
<Image
{...props}
style={[
StyleSheet.absoluteFill,
{
width: style.width,
height: style.height,
},
imageStyle,
]}
ref={imageRef}
/>
{children}
</View>
傳入的數(shù)據(jù)有children, style, imageStyle, imageRef
還有其它代表剩余屬性值的...props
,可以看到烛愧,傳入的style直接作用在<View>
組件上并不作用在<Image>
油宜,children
是與<Image>
平級的子組件掂碱,imageStyle和其它屬性值比如source直接傳入Image
組件,這里的imageStyle
就是我們需要注意的慎冤,因?yàn)樗邮盏臉邮綍?huì)作用于<Image>
疼燥,這里的StyleSheet.absoluteFill
來自于react-native/Libraries/StyleSheet/StyleSheet.js
const absoluteFillObject = {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
};
const absoluteFill = ReactNativePropRegistry.register(absoluteFillObject); // This also freezes it
這里的<Image>
是絕對定位,并且會(huì)填充整個(gè)<View>
扮演背景圖片蚁堤,也就是說imageStyle
就是背景圖片的樣式醉者,然而,官方文檔并未指明這樣一個(gè)隱藏的重要屬性披诗。
例子
<ImageBackground
source={{url:".../profile" }}
style={{
width: 150,
height: 150,
justifyContent: "center",
alignItems: "center"
}}
>
<Text style={{ color: "white" }}>hello vincent</Text>
</ImageBackground>
imageStyle={{
borderColor: "grey",
borderWidth: 2,
borderRadius: 75
}}
謝謝~