Hooks作用就是让我们在函数组件中可以使用类组件的一些特性:
比如state 、部分生命周期 、 context
useState作用: 可以让我们在函数组件中使用state和修改state
import React,{ useState } from 'react'
import { Button } from 'antd-mobile'
/* 函数组件 */
const HookComp = props => {
// useState 用法
let [ count, setCount ] = useState( 0 )
// 定义了一个初始值为0的state count,并且定义了一个修改count的方法
return (
<div className = "container">
<h3> 计数案例 </h3>
<Button type = "primary" onClick = {() => { setCount( count += 1 ) }}> +1 </Button>
<p> count的值为:{ count } </p>
</div>
)
}
export default HookComp
useEffect作用:可以让我们在函数组件中使用类似生命周期的功能: componentDidMount componentDidUpdate componentWillUnmount
import React,{ useState,useEffect } from 'react'
import { Button } from 'antd-mobile'
import Swiper from 'swiper'
/* 函数组件 */
const HookComp = props => {
let [ swiper,setSwiper ] = useState( null )
// useEffect( 回调函数 )
useEffect(() => {
// 我们的代码写在这里面
// 我们可以得到真实DOM
console.log('执行')
if ( !swiper ) {
console.log('swiper',swiper)
setSwiper( swiper = new Swiper ('.swiper-container', {
loop: true, // 循环模式选项
// 如果需要分页器
pagination: {
el: '.swiper-pagination',
},
// 如果需要前进后退按钮
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
// 如果需要滚动条
scrollbar: {
el: '.swiper-scrollbar',
},
}) )
}
})
return (
<div className = "container">
<div className="swiper-container" style = {{
width: '100%',
height: '2.1rem'
}} >
<div className="swiper-wrapper">
<div className="swiper-slide">Slide 1</div>
<div className="swiper-slide">Slide 2</div>
<div className="swiper-slide">Slide 3</div>
</div>
<div className="swiper-pagination"></div>
<div className="swiper-button-prev"></div>
<div className="swiper-button-next"></div>
<div className="swiper-scrollbar"></div>
</div>
</div>
)
}
export default HookComp
useContext作用:接收一个 context 对象(React.createContext 的返回值)并返回该 context 的当前值
//在src目录下--context/index.js
import React from 'react'
export const moneyContext = React.createContext()
//hooks/index.js
import React,{ useState } from 'react'
import Big from './Big'
import {
moneyContext
} from '@/context'
/*
static contextType = 定义context
*/
const HookComp = props => {
const [ money ] = useState( 2000 )
return (
<div className = "container">
<moneyContext.Provider value = { money }>
<Big/>
</moneyContext.Provider>
</div>
)
}
export default HookComp
//hooks/Big.js
import React from 'react'
import Small from './Small'
const Big = props => {
return (
<div>
<Small/>
</div>
)
}
export default Big
//hooks/Small.js
import React,{useContext} from 'react'
import { moneyContext } from '@/context'
const Small = props => {
const money = useContext( moneyContext )
return (
<div>
<p> 从HookComp组件传递过来的money值为: { money } </p>
</div>
)
}
export default Small