[技术博客]利用第三方框架react-native-swipeout实现左右滑动出现按钮

在之前的开发中,为了实现用户不同手势操作能够对应不同的功能,我们考虑使用React-Native的API——PanResponder,实现识别用户的手势,实现不同的功能。但我们很快就发现,这样简单的实现,无任何反馈的话,用户很难知道具有这样的功能。因此,我们准备实现类似手机QQ消息界面的左滑出现几个按钮。使用react-native的第三方框架react-native-swipeout可以很简单的实现此功能。

安装react-native-swipeout

框架的github地址: react-native-swipeout

可以使用npm install --save react-native-swipeoutyarn add react-native-swipeout命令安装框架

框架的使用

在框架的github项目中,开发者给出如下的示例代码

import Swipeout from 'react-native-swipeout';

// Buttons
var swipeoutBtns = [
  {
    text: 'Button'
  }
]

// Swipeout component
<Swipeout right={swipeoutBtns}>
  <View>
    <Text>Swipe me left</Text>
  </View>
</Swipeout>

阅读框架github项目中的文档,我们可以知道框架中实现了Swipeout组件,具有以下属性(props)

Prop Type Optional Default Description
autoClose bool Yes false 是否会自动关闭按钮列表
backgroundColor string Yes '#dbddde' 背景颜色
close bool Yes 当前列是否会关闭按钮
disabled bool Yes false 是否禁用swipeout
left array Yes [] 右滑时出现在左侧的按钮列表
onOpen func Yes (sectionID, rowId, direction: string) => void
按钮列表开启会执行的函数
onClose func Yes (sectionID, rowId, direction: string) => void
按钮列表关闭会执行的函数
right array Yes [] 左滑时出现在右侧的按钮列表
scroll func Yes prevent parent scroll
style style Yes style of the container
sensitivity number Yes 50 change the sensitivity of gesture
buttonWidth number Yes each button width

left和right属性应为形如[{ text: 'Button' }]的列表,其中支持的属性如下

Prop Type Optional Default Description
backgroundColor string Yes '#b6bec0' 按钮的背景颜色
color string Yes '#ffffff' 字体颜色
component ReactNode Yes null pass custom component to button
onPress func Yes null 按下后执行的函数
text string Yes 'Click Me' text
type string Yes 'default' default, delete, primary, secondary
underlayColor string Yes null 按时按钮背景颜色
disabled bool Yes false 是否禁用此按钮

具体使用代码

_renderItem = (item) => {
    var BtnsLeft = [{ text: '清空', type: 'delete',  onPress: ()=> console.log('清空列表')}];
    var BtnsRight = [{ text: '删除', type: 'delete', onPress: ()=>console.log('删除单行数据')}];

    return(
        <Swipeout
            close={!(this.state.sectionID === 'historylist' && this.state.rowID === Id)}
            right={BtnsRight}
            left={BtnsLeft}
            rowID={Id}
            sectionID='historylist'
            autoClose={true}
            backgroundColor='white'
            onOpen={(sectionId, rowId, direction: string) => {
                this.setState({
                    rowID: rowId,
                    sectionID: sectionId
                });
            }}
            scroll={event => console.log('scroll event') }
          >
        <View style={flatStylesWithAvatar.cell}
        >
        具体内容
        </View>
        </Swipeout>
    )
};

在渲染列表中的单行数据时,左右滑动可以出现不同操作的对应按钮,实现效果如下:

标签:技术积累

猜你喜欢

转载自www.cnblogs.com/PureMan6/p/10872165.html