目录

React基础之自定义hook函数

目录

React基础之自定义hook函数

自定义Hook是以use打头的函数,通过自定义Hook函数可以来实现逻辑的封装与复用

封装自定义hook的通用思路

1.声明一个以use大头的函数

2.在函数体内封装可复用的逻辑

3.把组件中用到的状态或者是状态以对象或是数组的形式return出去

4.在需要使用组件的地方,执行这个函数,结构出需要使用的状态和回调进行使用

import

React

, {

useState

}

from

‘react’

;

import

{

useEffect

}

from

‘react’

;

function

useToggle

(){

const

[

value

,

setValue

]=

useState

(

true

)

const

toggle

=()

=>

{

setValue

(!

value

)

}

//

那些状态和回调函数需要在其他组件中使用

return

return

{

value

,

toggle

}

}

function

App

() {

const

{

value

,

toggle

} =

useToggle

()

return

(

<

div

{

value

&&

<

div

this is div

</

div

}

<

button

onClick

=

{

toggle

}

toggle

</

button

</

div

);

}

export default

App

;

https://i-blog.csdnimg.cn/direct/2e86b96a99db45e68b66bf72192a52a8.png

ReactHooks使用规则

1.只能在组件中或其他自定义hook函数中调用

2.只能在组件的顶层调用,不能嵌套在if、for、其他函数中

import

React

, {

useState

}

from

‘react’

;

useState

(

''

)

//

错误的

function

App

() {

if

(

Math

.

random

()>

0.5

){

useState

(

''

)

//

错误的

}

return

(

<

div

</

div

);

}

export default

App

;