ImageBackground.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @flow
  8. * @format
  9. */
  10. 'use strict';
  11. const Image = require('./Image');
  12. const React = require('react');
  13. const StyleSheet = require('../StyleSheet/StyleSheet');
  14. const View = require('../Components/View/View');
  15. /**
  16. * Very simple drop-in replacement for <Image> which supports nesting views.
  17. *
  18. * ```ReactNativeWebPlayer
  19. * import React, { Component } from 'react';
  20. * import { AppRegistry, View, ImageBackground, Text } from 'react-native';
  21. *
  22. * class DisplayAnImageBackground extends Component {
  23. * render() {
  24. * return (
  25. * <ImageBackground
  26. * style={{width: 50, height: 50}}
  27. * source={{uri: 'https://reactnative.dev/img/opengraph.png'}}
  28. * >
  29. * <Text>React</Text>
  30. * </ImageBackground>
  31. * );
  32. * }
  33. * }
  34. *
  35. * // App registration and rendering
  36. * AppRegistry.registerComponent('DisplayAnImageBackground', () => DisplayAnImageBackground);
  37. * ```
  38. */
  39. class ImageBackground extends React.Component<$FlowFixMeProps> {
  40. setNativeProps(props: Object) {
  41. // Work-around flow
  42. const viewRef = this._viewRef;
  43. if (viewRef) {
  44. viewRef.setNativeProps(props);
  45. }
  46. }
  47. _viewRef: ?React.ElementRef<typeof View> = null;
  48. _captureRef = ref => {
  49. this._viewRef = ref;
  50. };
  51. render(): React.Node {
  52. const {children, style, imageStyle, imageRef, ...props} = this.props;
  53. return (
  54. <View
  55. accessibilityIgnoresInvertColors={true}
  56. style={style}
  57. ref={this._captureRef}>
  58. <Image
  59. {...props}
  60. style={[
  61. StyleSheet.absoluteFill,
  62. {
  63. // Temporary Workaround:
  64. // Current (imperfect yet) implementation of <Image> overwrites width and height styles
  65. // (which is not quite correct), and these styles conflict with explicitly set styles
  66. // of <ImageBackground> and with our internal layout model here.
  67. // So, we have to proxy/reapply these styles explicitly for actual <Image> component.
  68. // This workaround should be removed after implementing proper support of
  69. // intrinsic content size of the <Image>.
  70. width: style.width,
  71. height: style.height,
  72. },
  73. imageStyle,
  74. ]}
  75. ref={imageRef}
  76. />
  77. {children}
  78. </View>
  79. );
  80. }
  81. }
  82. module.exports = ImageBackground;