React Native中绝对定位元素的内容宽度

时间:2020-05-06 17:23:52

标签: reactjs react-native css-position absolute

我正在处理一些下拉组件,我想要实现的是一个按钮,当用户单击它时,应该会出现一个下拉组件。 包含按钮和下拉组件的父包装器应具有按钮的宽度和高度。出现下拉菜单时,它具有父级宽度,这是错误的。 我想对儿童的宽度进行拉伸,以免硬编码宽度也无济于事。 我当时在考虑适合内容,但不确定RN是否支持。

 <View style={{ width: 40, height: 40, backgroundColor: 'green' }}>
     // How to make its width based on max children width?
     <View style={{ backgroundColor: 'black', position: 'absolute', left: 50, top: -15 }}>
      <Text style={{color: 'white'}}>Item 1</Text>
      <Text style={{color: 'white'}} >Item long long 2</Text>
      <Text style={{color: 'white'}} >Item 3</Text>
      <Text style={{color: 'white'}} >Item long long4 2</Text>
     </View>
  </View>

这里是Example

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

您可以简单地将列表移到外部,并将按钮和列表都包装在视图中,并有条件地渲染下拉列表。这就是示例组件的外观。

const CustomDropDown = () => {
  const [showItem,setShowItem]=useState(false);
  return (
     <View>
      <TouchableOpacity style={{ width: 40, height: 40, backgroundColor: 'green' }} 
      onPress={()=>{setShowItem(!showItem)}}>

      </TouchableOpacity>
      {
        showItem &&
        <View style={{ backgroundColor: 'black', position: 'absolute', left: 50, top: -15 }}>
          <Text style={{color: 'white'}}>Item 1</Text>
          <Text style={{color: 'white'}} >Item long long 2</Text>
          <Text style={{color: 'white'}} >Item 3</Text>
          <Text style={{color: 'white'}} >Item long long4 2</Text>
        </View>
      }
      </View>
  );
};
相关问题