**新建项目命令 **
npx create-react-app my-app
cd my-app
npm start
# package.json 添加域名
"proxy": "blog.zdldove.top",
生命周期
此处只有一些常用的,具体查看官方文档
//存在期
componentWillReceiveProps(nextProps) {
console.log(this.props,nextProps);
}
shouldComponentUpdate(nextProps,nextState){
console.log("优化的生命周期只写了");
return true
}
//更新期
componentWillUpdate(nextProps,nextState){
console.log("待更新");
}
componentDidUpdate(prveProps,prveState,snapshot){
console.log("更新完成");
}
//销毁期
componentWillUnmount() {
console.log("即将卸载");
}
componentDidMount(){
//`componentDidMount()` 会在组件挂载后(插入 DOM 树中)立即调用。依赖于 DOM 节点的初始化应该放在这里。如需通过网络请求获取数据,此处是实例化请求的好地方。
}
SWiper
第一段是自己写的一段swiper,如果使用Swiper组件需要修改一部分代码,可看下一段(仅供参考)
import React, { Component } from 'react'
import "../App.css"
export class Home extends Component {
state = {
list: [
'/logo192.png', '/1.png', '/2.png'
],
img: '/logo192.png', //初始图片
index: 0 //初始下标
}
chageImg = () => {
let count = 0 //定义初始值
setInterval(() => {
//判断初始下标是否大于最大下标
if (this.state.index >= this.state.list.length - 1) {
//初始值重置
count = 0
//修改初始下标
this.setState({
index: count
})
} else {
//初始值++
count++
//修改初始下标
this.setState({
index: count
})
}
//修改图片
this.setState({
img: this.state.list[this.state.index]
})
}, 1000)
}
componentDidMount() {
//初始化执行
this.chageImg()
}
render() {
return (
<div>
<div className='banner'>
<img src={this.state.img} onClick={this.chageImg} />
</div>
</div>
)
}
}
export default Home
使用Swiper组件(仅供参考),具体查看官网 官方文档
import React, { Component } from 'react'
import { Carousel } from 'antd';
import swiper from "swiper"
import "swiper/css/swiper.css"
export class Swiper extends Component {
container = React.createRef()
pagination = React.createRef()
componentDidMount() {
new Swiper('.swiper-container', {
loop: true,
autoplay: {
delay: 1000,
stopOnLastSlide: true,
disableOnInteraction: true,
},
pagination: {
el: '.swiper-pagination',
},
})
}
render() {
return (
<div ref={this.container} className="swiper-container" style={{ width: 300, height: 300 }}>
<div className="swiper-wrapper" style={{ width: '100%', height: '100%' ,overflow:'hidden'}}>
{
React.Children.toArray(this.props.list).map((v,i)=>{
return <div style={{width:'100%',height:'100%'}} className="swiper-slide" key={i}>
<img src={v} style={{width:'100%',height:'100%'}}/>
</div>
})
}
</div>
<div ref={this.pagination} className="swiper-pagination"></div>
{/* <!--分页器。如果放置在swiper外面,需要自定义样式。--> */}
</div>
)
}
}
export default Swiper