繁体   English   中英

如何在 React Native 中的图像右侧创建一个 2x2 按钮部分的布局?

[英]How can I create a layout where there is a 2x2 button section to the right of an image in React Native?

这就是我想要创造的。

我已经尝试了很多使用容器的组合,以至于我不知道还能做什么。 此外,所有按钮必须具有相同的尺寸,并且按钮部分必须延伸到屏幕的末端。

  • 从具有 flexDirection 行的parentContainer开始,以便项目从左到右而不是上下放置。
  • parentContainer添加两个视图: imageContainerbuttonContainer 根据您的布局需求在两者之间划分宽度(来自问题的图像建议 50%/50%)
  • 将居中 styles 添加到imageContainer并使用onLayout确定图像的宽度和高度。
  • 将行 flexDirection 和 flexWrap 添加到buttonContainer
  • 创建一个 buttonStyle 确保它的宽度为 50%

这是一种将这一切结合在一起的小吃

import * as React from 'react';
import { Image, Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';

const Button = ({ title, titleStyle, ...touchableProps }) => {
  return (
    <TouchableOpacity
      {...touchableProps}
      style={[styles.button, touchableProps.style]}>
      <Text style={[{ textAlign: 'center' }, titleStyle]}>{title}</Text>
    </TouchableOpacity>
  );
};

export default function App() {
  // used to set image size
  const [{ width, height }, setViewDimensions] = React.useState({});
  // update image size on imageview layout chagnes
  const onLayout = ({ nativeEvent: { layout } }) => setViewDimensions(layout);
  return (
    <View style={styles.container}>
      <View style={styles.parentContainer}>
        <View style={styles.imageContainer} onLayout={onLayout}>
          <Image
            source={require('./assets/snack-icon.png')}
            style={{ width, height: width }}
            resizeMode="contain"
          />
        </View>
        <View style={styles.buttonContainer}>
          <Button title="1" />
          <Button title="2" />
          <Button title="3" />
          <Button title="4" />
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  parentContainer: {
    flex: 1,
    flexDirection: 'row',
  },
  imageContainer: {
    width: '50%',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'lightblue',
  },
  buttonContainer: {
    width: '50%',
    backgroundColor: 'lightgreen',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  button: {
    width: '50%',
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: 'white',
    borderBottomWidth: 1,
    borderRightWidth: 1,
  },
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM