react通过react-swipeable-views创建公共轮播图组件

文章展示了如何在React项目中引入react-swipeable-views库来创建一个轮播图组件。首先安装依赖,接着创建组件结构,编写jsx和css代码。组件接受高度、宽度和图片数组作为参数,并提供了默认值。最后在App组件中引用并显示轮播图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先创建一个react项目 然后引入依赖

npm install --save react-swipeable-views

然后我们的第三方插件就进来了
在这里插入图片描述
在项目src目录下创建目录 components

在项目创建 rotationChart 目录

然后在 rotationChart 目录下创建组件 index.jsx 还有他的样式文件 index.css

然后 index.jsx 编写代码如下

import React from 'react';
import SwipeableViews from 'react-swipeable-views';

import './index.css';

export default class Swiper extends React.Component{
    render(){
        const banners = this.props&&this.props.banners?this.props.banners:[];
        const height = this.props&&this.props.height?this.props.height:"200px";
        const width = this.props&&this.props.width?this.props.width:"400px";
        return (
            <div className = "swiper" style = { {height,width} }>
                <SwipeableViews>
                     {
                        banners.map((element ,index) => {
                            return (
                                <div className='swiper-view' key= { index }>
                                    <img src={ element } alt=""/>
                                </div>
                            )
                        })
                     }
                </SwipeableViews>
            </div>
        )
    }
}

然后 编写 index.css参考代码如下

.swiper{
    position: relative;
}
*{
    width: 100%;
    height: 100%;
}

然后 在 App组件中引用这个轮播图组件看效果 参考代码如下

import './App.css';
import React from "react";
import RotationChart from "./components/rotationChart";

let img1 = "https://img1.baidu.com/it/u=413643897,2296924942&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500";
let img2 = "https://img1.baidu.com/it/u=3539595421,754041626&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500";
let img3 = "https://img2.baidu.com/it/u=1361506290,4036378790&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500"
export default class App extends React.Component{
  constructor(props){
    super(props);
    this.state = {
    }
  }

  render(){
    return (
      <div>
          <span>轮播图</span>
          <RotationChart height = { "50vh" } width = { "100vh" } banners = { [img1,img2,img3] }/>
      </div>
    )
  }
}

我们这个组件 接受三个参数 分别是 高度 宽度 还有一个就是 数组 数组的每一个下班都必须是一个图片的地址

这三个参数我前面都有给默认值 都可以不传

然后 运行结果如下
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值