Skip to content

Instantly share code, notes, and snippets.

@blackmiaool
Last active July 7, 2017 09:53
Show Gist options
  • Save blackmiaool/5a6f8e3e4626b4bfc11a269062d0a606 to your computer and use it in GitHub Desktop.
Save blackmiaool/5a6f8e3e4626b4bfc11a269062d0a606 to your computer and use it in GitHub Desktop.
sync react native component height
usage:
static propTypes = {
SyncHeight: PropTypes.any,
}
static defaultProps = {
SyncHeight: View
}
render(){
return (<SyncHeight name="product" style={styles.productImage}>
<Touchable type="opacity" onPress={this.handlePress} activeOpacity={0.8}>
<CommonImage width={this.props.baseWidth} source={{ uri: pic }} />
</Touchable>
</SyncHeight>);
}
const heightMap = {};
class SyncHeight extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
children: PropTypes.object.isRequired,
style: PropTypes.oneOfType([
PropTypes.number,
PropTypes.object,
]),
}
static defaultProps={
style: {}
}
constructor(...args) {
super(...args);
this.state = { minHeight: 0 };
this.setHeight = this.setHeight.bind(this);
this.onLayoutWrap = this.onLayoutWrap.bind(this);
}
onLayout(height, name) {
const style = StyleSheet.flatten(this.props.style);
let bonus = 0;
if (style.borderWidth) {
bonus += style.borderWidth * 2;
}else {
if (style.borderTopWidth) {
bonus += style.borderTopWidth;
}
if (style.borderTopWidth) {
bonus += style.borderBottomWidth;
}
}
height += bonus;
if (!heightMap[name]) {
heightMap[name] = {
height,
queue: [],
};
}
const target = heightMap[name];
target.queue.push(this.setHeight);
if (height <= target.height) {
this.setHeight(target.height);
return;
}
target.height = height;
target.queue.forEach((cb) => {
if (cb !== this.setHeight) {
cb(height);
}
});
}
onLayoutWrap(event) {
if (event.nativeEvent && event.nativeEvent.layout) {
const height = event.nativeEvent.layout.height;
this.onLayout(height, this.props.name);
}
}
setHeight(minHeight) {
this.setState({
minHeight
});
}
render() {
return (<View style={[this.props.style, { minHeight: this.state.minHeight }]}>
<View onLayout={this.onLayoutWrap}>
{this.props.children}
</View>
</View>);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment