React Native - 圖片



在本章中,我們將瞭解如何在 React Native 中處理圖片。

新增圖片

讓我們在 src 資料夾內建立一個新的資料夾 img。我們將在該資料夾內新增我們的圖片 (myImage.png)。

我們將在主螢幕上顯示圖片。

App.js

import React from 'react';
import ImagesExample from './ImagesExample.js'

const App = () => {
   return (
      <ImagesExample />
   )
}
export default App

可以使用以下語法訪問本地圖片。

image_example.js

import React, { Component } from 'react'
import { Image } from 'react-native'

const ImagesExample = () => (
   <Image source = {require('C:/Users/Tutorialspoint/Desktop/NativeReactSample/logo.png')} />
)
export default ImagesExample

輸出

React Native Images

螢幕密度

React Native 提供了一種使用 @2x、@3x 字尾為不同裝置最佳化圖片的方式。程式只加載特定螢幕密度需要的圖片。

以下將是 img 資料夾中圖片的名稱。

my-image@2x.jpg
my-image@3x.jpg

網路圖片

使用網路圖片時,需要 source 屬性,而不是 require。建議為網路圖片定義 widthheight

App.js

import React from 'react';
import ImagesExample from './image_example.js'

const App = () => {
   return (
      <ImagesExample />
   )
}
export default App

image_example.js

import React, { Component } from 'react'
import { View, Image } from 'react-native'

const ImagesExample = () => (
   <Image source = {{uri:'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'}}
   style = {{ width: 200, height: 200 }}
   />
)
export default ImagesExample

輸出

Network Images
廣告