[英]React Native Image component source as ES6 import images
是否可以導入圖像並在<Image />
組件的source
中使用它們?
基於 state,我有很多地方需要有條件地顯示圖標或其他圖標。 例如:
{isToggled ? (
<Image
resizeMode='contain'
source={require('../../assets/images/icon_chevron_up_B82BF9.png')}
style={styles.toggleArrowImage}
/>
) : (
<Image
resizeMode='contain'
source={require('../../assets/images/icon_chevron_down_B82BF9.png')}
style={styles.toggleArrowImagew}
/>
)}
或者
const getToogleImageSource = () => {
if (isToggled) {
return require('../../assets/images/icon_chevron_up_B82BF9.png')
}
return require('../../assets/images/icon_chevron_down_B82BF9.png')
}
...
<Image
resizeMode='contain'
source={getToogleImageSource()}
style={styles.toggleArrowImagew}
/>
查看Image 上的 React Native 文檔,並在 StackOverflow 上搜索它,我總是看到使用require
來獲取源代碼的解決方案。
因此,我對使用這樣的 ES6 導入來減少代碼行數的問題(我也發現它更容易閱讀):
import chevronDown from ('../../assets/images/icon_chevron_down_B82BF9.png')
import chevronUp from ('../../assets/images/icon_chevron_up_B82BF9.png')
...
<Image
resizeMode='contain'
source={isToggled ? chevronUp : chevronDown}
style={styles.toggleArrowImagew}
/>
我在本地對其進行了測試,它工作正常,所以我想知道這是否會導致獨立應用程序出現問題,因為打包程序或我忽略的東西。
僅供參考,我在 app.json 中有這個:
"assetBundlePatterns": [
"assets/images/*"
],
謝謝你的幫助。
[編輯]:我忘了提到我正在使用 Expo
在 react-native 應用程序中使用圖像時,我使用以下方法。 雖然這仍然使用required
關鍵字,但我得到了您也在尋求的以下優勢。
required
關鍵字的能力。這是具有 3 個簡單步驟的實現。
assets
目錄中定義一個索引文件(index.tx)
。 如果您使用的是 js index.js
在索引文件中進行所有導入
const images = { logo: require('./logo.png'), splash_image: require('./splash_image.png'), chevronUp: require('./chevronUp.png'), chevronUp: require('./chevronDown.png'), } export default images;
將index.tx
導入您的組件並按如下方式使用。 您可以使用image.filename
使用任何圖像。 並且組件中不再require
關鍵字。
import images from '../../../assets'; ... <Image resizeMode='contain' source={isToggled? images.chevronUp: images.chevronDown} style={styles.toggleArrowImagew} />
希望這就是你要找的:D
嘗試import
后更新
只需在組件頂部按如下方式導入圖像。
import { ... , Image } from 'react-native';
import img_welcome from '../../images/welcome.png';
...
<Image source={img_welcome} />
這對我來說非常有用。
我在 app.json 中沒有任何內容,除了 appnames
我從您的代碼和我的工作代碼中看到的唯一區別是
import
語句中有一對圓括號()
干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.