如何在React Native中将浮动操作按钮置于右下角

4
我正在尝试在我的应用程序的右下角放置一个浮动操作按钮,但是它却将其放在了屏幕的左上方,偏离了屏幕。

返回视图:

<View>
   <View style={{flexDirection: 'row'}}>
      <TouchableOpacity onPress={this.onPress} activeOpacity={.5} >
          <Image
              source={require('./assets/images/hamburger.png')}
              style={{ width: 30, height: 25,  marginLeft: 15}}
          />
      </TouchableOpacity>
   </View>
   <FloatingAction style={styles.bottom}/>
</View>

样式:

const styles = StyleSheet.create({
  bottom: {
    flex: 1,
    position: 'absolute',
    bottom: 10,
    right:10
  },
});

我的当前视图显示了一个标题和底部选项卡视图。我能够在每个选项卡屏幕中放置多个浮动操作按钮,但那会产生不良行为。感谢任何帮助。

编辑: 我的现状如图所示:

我想要的效果如下图所示:


你能分享一些你所拥有和需要的截图吗? - DevAS
@Dev更新了,清楚吗? - David
尝试在父视图中添加flex:1。 - VolkanSahin45
1
尝试从styles.bottom中删除flex:1。这样做的想法是将浮动操作按钮添加到填充整个屏幕的主区域中。 - VolkanSahin45
1
好的,@VolkanSahin45。 - DevAS
显示剩余11条评论
3个回答

8

您的问题是在将{ flex: 1, position: 'absolute',}添加到按钮样式中。覆盖整个手机屏幕的父组件将使用flex: 1,您的按钮组件是接收位置样式的那个。

始终创建新组件可以使事情更易于阅读和理解。因此,假设您有一个按钮组件(<FloatingButton/>),您可以这样做:

import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import FloatingButton from './FloatingButton';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>
          I'm just a Text
        </Text>

        <FloatingButton 
          style={styles.floatinBtn}
          onPress={() => alert(`I'm being clicked!`)}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  floatinBtn: {
    
    position: 'absolute',
    bottom: 10,
    right: 10,
  }
});

您将获得此结果: 这是按钮组件:
import React from 'react';
import { View, TouchableOpacity } from 'react-native';

export default props => (
  <TouchableOpacity onPress={props.onPress} style={props.style}>
    <View
      style={{
        backgroundColor: 'blue',
        width: 45,
        height: 45,
        borderRadius: 45,
      }}
    />
  </TouchableOpacity>
);

请查看小吃演示:https://snack.expo.io/@abranhe/floating-btn


1
// this should occupy the whole screen
<View style={{flex:1}}>
   <View style={{flexDirection: 'row'}}>
      <TouchableOpacity onPress={this.onPress} activeOpacity={.5} >
          <Image
              source={require('./assets/images/hamburger.png')}
              style={{ width: 30, height: 25,  marginLeft: 15}}
          />
      </TouchableOpacity>
   </View>
   <FloatingAction style={styles.bottom}/>
</View>
const styles = StyleSheet.create({
  bottom: {
    position: 'absolute',
    bottom: 10,
    right:10
  },
});

0

在你的代码中使用这个CSS:

.floating-btn {
  position:fixed;
  bottom:10;
  right: 10;
}

就是这样


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