はじめに
React Nativeで、親要素の高さを超えて小要素を表示させたいとき、iOSではうまくいくのですがAndroidではうまくいきませんでした。
iOS | Android |
---|---|
![]() |
![]() |
こちらの画像のコードは以下のようになっています。
class App extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.outer}>
<View style={styles.upperBox}>
<Text>Upper Box</Text>
</View>
</View>
</View>
);
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
outer: {
width: 200,
height: 150,
backgroundColor: '#AEC4E5',
borderWidth: 2,
borderColor: '#666',
overflow: 'visible', // この部分を省略してもiOSでは小要素がはみ出て表示されます
},
upperBox: {
width: 100,
height: 300,
backgroundColor: '#EB8686',
},
});
調べたところ、現バージョンのReact NativeのAndroidでは overflow: 'visible'
が効かないそう。
しかし、どうしても親要素の高さを超えて小要素を表示させる(ように見せる)必要があったので、いろいろと試行錯誤してみました。
今回はその方法を書き残そうと思います。
対象バージョン
- react-native-cli: 2.0.1
- react-native: 0.55.2
【解決方法1】 position を使う
position を使って、要素の位置をずらしてうまく配置します。
class App extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.outer} />
<View style={styles.upperBox}>
<Text>Upper Box</Text>
</View>
</View>
);
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
outer: {
width: 200,
height: 150,
backgroundColor: '#AEC4E5',
borderWidth: 2,
borderColor: '#666',
position: 'relative',
},
upperBox: {
width: 100,
height: 300,
backgroundColor: '#EB8686',
position:'absolute',
top: 106,
},
});
ポイントは、親要素だった <View style={styles.container}>
から、小要素の <View style={styles.upperBox}>
を外に出してあげること。
Androidでは現段階で、親要素の高さを超えて小要素を表示させることができないので、小要素を外に出してあげる必要があります。
これでどちらのOSでも同じように、親要素の高さを小要素が超えて表示されているように見せることができました。
(<View style={styles.container}>
のflexによって、小要素が中央に寄っています)
iOS | Android |
---|---|
![]() |
![]() |
【解決方法2】 marginTop にマイナス値を指定して、要素を上に引き上げる
もう1つの解決方法は、marginTopにマイナス値を指定することです。
マイナス値を指定することで、要素が上に引き上げられ、重なって表示されるようになります。
class App extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.outer} />
<View style={styles.upperBox}>
<Text>Upper Box</Text>
</View>
</View>
);
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
outer: {
width: 200,
height: 150,
backgroundColor: '#AEC4E5',
borderWidth: 2,
borderColor: '#666',
},
upperBox: {
width: 100,
height: 300,
backgroundColor: '#EB8686',
marginTop: -302
},
});
これで【解決方法1】と同じように表示されるようになりました!
おわりに
個人的には marginTop
で要素を引き上げるというのは何となく違和感があるのですが、
position
を使うよりもズレが生じにくい気がするので、marginTop
で引き上げる方法のほうが良さそうだなと思っています。
(実際のアプリ開発ではmarginTop
にマイナス値を指定する方法で乗り切りました…)