react左右滑动组件
时间: 2023-09-06 19:12:42 浏览: 47
你可以使用 React Swipeable 这个开源库来实现左右滑动组件。这个库提供了简单易用的 API,并且对移动端和桌面端都有良好的支持。
以下是一个简单的示例:
```jsx
import React from 'react';
import { Swipeable } from 'react-swipeable';
class SwipeableComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
currentIndex: 0,
items: [
{
id: 1,
content: 'Item 1',
},
{
id: 2,
content: 'Item 2',
},
{
id: 3,
content: 'Item 3',
},
],
};
}
handleSwipeLeft = () => {
const { currentIndex, items } = this.state;
if (currentIndex + 1 < items.length) {
this.setState({
currentIndex: currentIndex + 1,
});
}
};
handleSwipeRight = () => {
const { currentIndex } = this.state;
if (currentIndex > 0) {
this.setState({
currentIndex: currentIndex - 1,
});
}
};
render() {
const { currentIndex, items } = this.state;
return (
<Swipeable
onSwipedLeft={this.handleSwipeLeft}
onSwipedRight={this.handleSwipeRight}
>
<div>
<h2>{items[currentIndex].content}</h2>
</div>
</Swipeable>
);
}
}
export default SwipeableComponent;
```
在这个例子中,我们使用了 `Swipeable` 组件来监听左右滑动事件,并在回调函数中更新了当前显示的项目。
你可以根据自己的需求来修改这个示例,添加更多的项目或者自定义样式等。