【问题标题】:React Native: How to stretch TouchableOpacityReact Native:如何拉伸 TouchableOpacity
【发布时间】:2021-03-16 05:19:17
【问题描述】:

我试图让两个大按钮 (TouchableOpacity) 彼此相邻并占据屏幕宽度的 50%。

但它们似乎只与其中的文本组件一样宽。

如何让两个 TouchableOpacity 占据整个屏幕的宽度,每个占据 50% 的宽度?

  const styles = StyleSheet.create({
    container: {
      flexDirection: 'row',
      backgroundColor: 'lightblue',
      height: 200,
      justifyContent: 'space-around',
    },
    btn: {
      flex: 1,
      backgroundColor: 'red',
      justifyContent: 'center',
      padding: 20,
      borderWidth: 1,
    },
  });

  return (
    <View style={styles.container}>
      <TouchableOpacity style={styles.btn}>
        <Text>Left</Text>
      </TouchableOpacity>

      <TouchableOpacity style={styles.btn}>
        <Text>Right</Text>
      </TouchableOpacity>
    </View>
  );

【问题讨论】:

    标签: react-native


    【解决方案1】:

    尝试为你的 btn 类添加 50% 的宽度

      const styles = StyleSheet.create({
        container: {
          flexDirection: 'row',
          backgroundColor: 'lightblue',
          height: 200,
          justifyContent: 'space-around',
        },
        btn: {
          width: '50%',
          backgroundColor: 'red',
          padding: 20,
          borderWidth: 1,
        },
      });
    
    

    您也可以使用 react native 中的 dimensions 并将 width: windowWidth/2 放在您的 btn 类中。

    【讨论】:

      【解决方案2】:

      一个可能的解决方案是使用 react native 的Dimensions

      https://reactnative.dev/docs/dimensions

        import { Dimensions } from 'react-native';
      
        const width = Dimensions.get('window').width;
      
        const styles = StyleSheet.create({
          container: {
            flexDirection: 'row',
            backgroundColor: 'lightblue',
            height: 200,
            justifyContent: 'space-around',
          },
          btn: {
            width: width*0.5,
            backgroundColor: 'red',
            padding: 20,
            borderWidth: 1,
          },   
        });
      

      【讨论】:

      • 这很有效,谢谢。 (我最终按照链接中的建议使用了useWindowDimensions()。)虽然我觉得这应该是可能的,无需测量宽度,只需使用 CSS。
      猜你喜欢
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      • 2019-06-17
      • 1970-01-01
      • 2015-07-28
      • 2018-01-26
      相关资源
      最近更新 更多