对此有两种方法。一种是将所有内容放在开始和结束<Image> 标签之间。另一种是使用布局属性。参考这个链接:https://medium.com/reactnative/background-images-in-react-native-191f3ed95a45
第一种方式是使用<Image>作为容器。将您的内容放在<Image> 和</Image> 之间。一定要设置内容的backgroundColor: 'transparent'。我认为Android默认提供它,但iPhone没有。因此,为了保持一致性,我们需要明确声明它。 React Native 会警告你这样做。它很快就会变成一个错误。所以,我推荐后一种方式。
const remote = 'https://s15.postimg.org/tw2qkvmcb/400px.png';
export default class BackgroundImage extends Component {
render() {
const resizeMode = 'center';
const text = 'This is some text inlaid in an <Image />';
return (
<Image
style={{
backgroundColor: '#ccc',
flex: 1,
resizeMode,
position: 'absolute',
width: '100%',
height: '100%',
justifyContent: 'center',
}}
source={{ uri: remote }}
>
<Text
style={{
backgroundColor: 'transparent',
textAlign: 'center',
fontSize: 30,
padding: 40,
}}
>
{text}
</Text>
</Image>
);
}
}
第二种方法是使用布局属性。在容器中获取<View> 并设置{position:'absolute', width: '100%', height: '100%'}。在这个<View> 中插入<Image> 并设置flex: 1。您可能还想添加resizeMode。现在在同一个容器中写一个兄弟<View> 并设置{flex: 1, backgroundColor: 'transparent'}。在这个兄弟<View> 中放置您的内容。您可能希望为<Image> 或兄弟<View> 设置opacity。
示例如下:
const remote = 'https://s15.postimg.org/tw2qkvmcb/400px.png';
export default class BackgroundImage extends Component {
render() {
const resizeMode = 'center';
const text = 'I am some centered text';
return (
<View
style={{
flex: 1,
backgroundColor: '#eee',
}}
>
<View
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
}}
>
<Image
style={{
flex: 1,
resizeMode,
}}
source={{ uri: remote }}
/>
</View>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
justifyContent: 'center',
}}
>
<Text
style={{
textAlign: 'center',
fontSize: 40,
}}
>
{text}
</Text>
</View>
</View>
);
}
}