[英]return view based on getimagesize - react-native
我有以下代碼:
getPhoto(item) {
Image.getSize( 'http://api/people/' + item.id + '/photo', ( width, height ) =>
{
this.setState({ imageWidth: width, imageHeight: height });
console.log('http://api/people/' + item.id + '/photo', + ' ' + 'width: ' + width)
},(errorMsg) =>
{
console.log('http://api/people/' + item.id + '/photo', + ' ' + ' errorMsg: ' + errorMsg.code);
this.setState({ imageError: errorMsg.code });
});
//console.log('http://api/people/' + item.id + '/photo', + ' ' + ' errorMsg: ' + this.state.imageError + ' ' + ' errorMsgIncludes: ' + this.state.imageError.includes('ERCTERRORDOMAIN0'));
return (
<TouchableOpacity>
<ListItem style={styles.listItem}>
<FastImage
style={styles.avatar}
source={{
uri: 'http://api/people/' + item.id + '/photo',
priority: FastImage.priority.high,
}}
resizeMode={FastImage.resizeMode.strech}
/>
<View style={styles.multiLineView} >
<Text style={styles.name}>{item.id}</Text>
</View>
</ListItem>
</TouchableOpacity>
)
}
這里的問題是setstate不會在成功和錯誤回調之外持續存在,因此我得到了不合適的結果。
如何在這些回調函數中呈現視圖?
先謝謝您的幫助!!
我認為您應該稍微重構代碼,然后將獲取照片功能邏輯移至新組件
export default class Item extends React.Component{
constructor(props){
super(props);
this.state={imageWidth: 0, imageHeight: 0}
}
// make the call for get size inside component did mount
componentDidMount(){
let item = this.props.item;
Image.getSize( 'http://api/people/' + item.id + '/photo', ( width, height
) =>
{
this.setState({ imageWidth: width, imageHeight: height });
console.log('http://api/people/' + item.id + '/photo', + ' ' + 'width:
' + width)
},(errorMsg) =>
{
console.log('http://api/people/' + item.id + '/photo', + ' ' + ' errorMsg: ' + errorMsg.code);
this.setState({ imageError: errorMsg.code });
});
}
render(){
// render the view you want here according to the component state
switch(this.state.acondition){
case 1:
return a view or component you want ...
etc ...
}
}
}
然后您可以調用組件並像這樣傳遞項目
import Item from './Item';
<Item item={item}/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.