arm-components
Version:
components for react-native
96 lines (89 loc) • 2.36 kB
JavaScript
import React, { Component } from 'react';
import { Image } from 'react-native';
export default class ImageBlock extends Component{
constructor(props){
super(props);
this.state = {
url : this.props.url,
propsWidth: this.props.width,
propsHeight: this.props.height,
width: 0,
height: 0,
borderRadius: this.props.borderRadius || 0,
onLayout: this.props.onLayout
}
}
componentWillReceiveProps(newProps){
let { url, propsWidth, propsHeight } = this.state;
this.addImageWidthHeight(newProps.url, newProps.width, newProps.height);
this.setState({
url: newProps.url,
propsWidth: newProps.width,
propsHeight: newProps.height,
borderRadius: newProps.borderRadius || 0
})
}
setSize(width, height, newWidth, newheight){
if (newWidth && !newheight) {
this.setState({
width: newWidth,
height: height * (newWidth / width)
});
} else if (!newWidth && newheight) {
this.setState({
width: width * (newheight / height),
height: newheight
});
} else {
this.setState({
width: width,
height: height
});
}
}
borderRadius(borderRadius){
if(typeof borderRadius === 'number'){
return {
borderRadius: borderRadius
}
}else if(typeof borderRadius === 'object'){
return {
borderTopLeftRadius: borderRadius.topLeft || 0,
borderTopRightRadius: borderRadius.topRight || 0,
borderBottomLeftRadius: borderRadius.bottomLeft || 0,
borderBottomRightRadius: borderRadius.bottomRight || 0
}
}else{
return {
borderRadius: 0
}
}
}
addImageWidthHeight(url, newWidth, newheight){
if (url.uri){
Image.getSize(url.uri, (width, height) => {
this.setSize(width, height, newWidth, newheight);
});
} else {
let {width, height} = Image.resolveAssetSource(url);
this.setSize(width, height, newWidth, newheight);
}
}
componentWillMount(){
let { url, propsWidth, propsHeight } = this.state;
this.addImageWidthHeight(url, propsWidth, propsHeight);
}
render(){
let { url, width, height, propsWidth, propsHeight, borderRadius, onLayout } = this.state;
return(
<Image
onLayout={onLayout}
source={url}
style={[
{ width: width, height: height },
this.borderRadius(borderRadius)
]}
/>
)
}
}