2016-04-29 76 views
2

我想調整listView行的相對於其內容的圖像和文本的大小, 圖像是遠程的,我正在從firebase中讀取它,並且正在顯示它與uri, 當我把一個寬度或高度的行,圖像顯示,但我想要做的是調整行的大小,以便它需要圖像的高度。listView關於其內容的行大小

我發現這個解決方案

var React = require('react-native'); 

var { 
AppRegistry, 
StyleSheet, 
View, 
Image 
} = React; 

var TestCmp = React.createClass({ 
render: function() { 
    return (
    <View style={styles.imageContainer}> 
     <Image style={styles.image} source={{uri: 'http://lorempixel.com/200/400/sports/5/![enter image description here][2]'}} /> 
     </View> 
    ); 
    } 
    }); 

var styles = StyleSheet.create({ 
    imageContainer: { 
    flex: 1, 
    alignItems: 'stretch' 
    }, 
    image: { 
    flex: 1 
} 
}); 

    AppRegistry.registerComponent('RCTTest',() => TestCmp); 

但它不使用ListView行工作

我也想給這ListView的行中的容器: 柔性:1, alignItems:「拉伸」, 左:0, 右:0, 高度:500,

和圖像: 撓曲:1,

但是當然圖像的高度爲500,並且它會被拉伸,因此它的某些部分將不可見。

+0

你會很高興提供一個小的RNPlay(https://rnplay.org/)片段顯示問題?這樣,其他人可以更容易地嘗試爲你解決問題;) –

回答

1

問題解決了! 保存我使用Image.getSize的問題,並計算相對於屏幕寬度的高度。 但Image.getSize是異步的,所以我做了以下操作: 1-I通過導入Dimensions並將其保存到變量中來計算屏幕的寬度。

var widthScreen = Dimensions.get('window').width; 

2 - 我加在美國2個空數組:一個叫「itemsForListView」,另一個是「物品」,你就會明白爲什麼在一段時間。

3-中實現讀取來自火力數據「listenForItems」的方法,我寫道:

listenForItems(itemsRef) { 
var index= 0; //to track the image 
// get children as an array 
itemsRef.on('value', (snap) => { 
    var items = []; 
    snap.forEach((child) => { 
    this.setState({ 
     items: this.state.items.concat([{ //I am adding the elements one by one to the state 
     title: child.val().title, 
     image: child.val().image, 
     year: child.val().year, 
     index: index, 
     _key: child.key(), 
     width: this.state.widthScreen, //give it the width of the screen as a variable 
     height:0 //for the moment because I can't calculate it 
     }])}); 
     this.getImageSize(child.val().image, index++); 
    }); 
    }); 
    } 


getImageSize(uri, ind) { 
Image.getSize(uri, (width, height) => { 
    //calculate the new height with respect to the width of the screen 
    this.state.items[ind].height = this.state.widthScreen * height/width; 
    this.setState({ 
    itemsForListView: this.state.itemsForListView.concat([ 
     this.state.items[ind] 
    ]) 
    }); 
//feed the listView with the ready image 
this.setState({ 
    dataSource: this.state.dataSource.cloneWithRows(this.state.itemsForListView) 
    }); 
}); 
} 

4-現在在列表視圖的renderRow方法,你可以使用item.width和item.height以便爲圖像提供所需的尺寸。

+0

謝謝,但它對我來說很困惑。我希望有一種方法可以指定「高度:AutoSize」(Xamarin風格)或類似的東西...... –