在之前的開發中,為了實現用戶不同手勢操作能夠對應不同的功能,我們考慮使用React-Native的API——PanResponder,實現識別用戶的手勢,實現不同的功能。但我們很快就發現,這樣簡單的實現,無任何反饋的話,用戶很難知道具有這樣的功能。因此,我們准備實現類似手機QQ消息界面的左滑出現幾個按鈕。使用react-native的第三方框架react-native-swipeout可以很簡單的實現此功能。
安裝react-native-swipeout
框架的github地址: react-native-swipeout
可以使用npm install --save react-native-swipeout
或 yarn 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>
)
};
在渲染列表中的單行數據時,左右滑動可以出現不同操作的對應按鈕,實現效果如下: