如何在 react native 中为图像指定多个 uri?

4 javascript android ios ecmascript-6 react-native

该文档说:

这个 prop 还可以包含几个远程 URL,连同它们的宽度和高度一起指定,并可能与比例/其他 URI 参数一起指定。

谁能告诉如何在 react-native 中为图像组件指定多个 URI?这个定义没有这样的例子。以及如何按照本文档所述将高度和宽度参数与 URI 一起传递。

Rob*_*zak 7

您可以在react-native源代码中找到答案,特别/node_modules/react-native/Libraries/Image是文件ImageSourcePropType和ImageProps.

根据ImageSourcePropType,当传递 URI 对象时,它应该是这种形状(意味着它可以具有任何定义的属性,只要类型与预期匹配):

const ImageURISourcePropType = PropTypes.shape({
  uri: PropTypes.string,
  bundle: PropTypes.string,
  method: PropTypes.string,
  headers: PropTypes.objectOf(PropTypes.string),
  body: PropTypes.string,
  cache: PropTypes.oneOf([
    'default',
    'reload',
    'force-cache',
    'only-if-cached',
  ]),
  width: PropTypes.number,
  height: PropTypes.number,
  scale: PropTypes.number,
});
Run Code Online (Sandbox Code Playgroud)

根据ImageProps, source允许一个 shapeImageSourcePropType的对象、这些对象的数组或一个数字(对于本地资产,该语句require('imgs/image1.png')返回一个标识该资产的数字)。这是代码:

const ImageSourcePropType = PropTypes.oneOfType([
  ImageURISourcePropType,
  // Opaque type returned by require('./image.jpg')
  PropTypes.number,
  // Multiple sources
  PropTypes.arrayOf(ImageURISourcePropType),
]);
Run Code Online (Sandbox Code Playgroud)

所以source道具将接受匹配的单个对象ImageURISourcePropType或的对象数组。

因此,要传递多个远程图像并指定宽度,它将类似于

<Image
  source={[
    {
      uri: 'https://image.location.com',
      width: 500,
      height: 500
    },
    {
      uri: 'https://image2.location.com',
      width: 600,
      height: 600
    },
    {
      uri: 'https://image3.location.com',
      width: 700,
      height: 700
    },
  ]}
/>
Run Code Online (Sandbox Code Playgroud)