如何在React Native中添加浮动按钮?

4
我想在React Native中添加浮动按钮。我使用了position: absolute,但是它显示在屏幕底部即内容结束的地方。我想将浮动按钮显示在右下角,并且在用户上下滚动屏幕时可见。
React Native Paper 提供了浮动按钮: https://callstack.github.io/react-native-paper/fab.html#usage 如果我使用position: 'fixed',会出现错误:https://imgur.com/a/JZJ7Pbl 代码:
<ScrollView>

// Some other View components 

     <FAB
        style={styles.fab}
        small
        color="#00d048"
        icon="add"
      />
</ScrollView>

CSS:

fab: {
        position: 'absolute',
        right: 0,
        bottom: 0,
    }

在截图中,您可以看到按钮没有浮动在内容上方,而是显示在屏幕底部。
截图: enter image description here
3个回答

8

React Native目前不支持position: fixed,因此我们需要在一个绝对定位的单独的View中添加该元素。由于我们仍然想要滚动其他内容,因此我们需要在另一个View中将这两个元素包装起来:

<View style={{flex: 1}}>
  <ScrollView>
   // Your other components here
  </ScrollView>
  <View style={styles.fixedView}>
    <Fab
      style={styles.fab}
      small
      color="#00d048"
      icon="add"
     />
  </View>
</View>

并且还有样式:

fixedView : {
  position: 'absolute',
  left: 0,
  bottom: 0,
  flexDirection: 'row',
  justifyContent: 'flex-end',
}

可以选择给Fab右下方一个整齐的边距。

fab: {
    margin-right: theme.spacing.unit * 2,
    margin-bottom: theme.spacing.unit * 3,
}

如果我使用position: 'fixed',那么我会得到这个效果,请查看https://imgur.com/a/JZJ7Pbl - fun joker
很好的观点 @funjoker,React Native不支持像ReactJS一样的position: fixed。如果更新的方法适用于您,请告诉我。 - Siavas
如果我想在左下角添加图标,该怎么做? - fun joker
2
将其添加到fixedView中,指定 justifyContent: space-between 而不是 flex-end,并从 fab 中删除 margin-right - Siavas

1

https://github.com/oblador/react-native-vector-icons

import {TouchableOpacity, Image} from 'react-native';

<TouchableOpacity
          style={{
            borderWidth: 1,
            borderColor: 'rgba(0,0,0,0.2)',
            alignItems: 'center',
            justifyContent: 'center',
            width: 70,
            position: 'absolute',
            bottom: 30,
            right: 10,
            height: 70,
            backgroundColor: '#fff',
            borderRadius: 100,
          }}
        >
          {/* <Icon name="plus" size={30} color="#01a699" /> */}
          <Image style={{width: 50, height:50,  resizeMode: 'contain'}} source={require('assets/imgs/group.png')} />
        </TouchableOpacity>
        </View>

1
如果您想使用position: absolute;,父元素必须为position: relative;

2
CSS默认值和React Native的默认值之间存在一些差异。例如,在React Native中,position: relative是默认值,而在CSS中则为static。并非所有的样式属性在React Native中都可用。 - Siavas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接