React 基础笔记(React使用自定义Hooks)(二十八)

自定义 Hooks

我们可以自定义 Hooks 这样增加了复用性

  • 自定义 Hooks 必须以 use 开头 否则不读取

  • 必须有返回值

父组件

import React from 'react'
import SecondComponent from './Second'
import UseHooks from './CutomHooks'
function App() {
  const [count, setcount] = UseHooks(0)
  function handleClick() {
    setcount(() => {
      return count + 1
    })
  }
  return (
    <div>
      <span>{count}</span>
      <button onClick={handleClick}>点击</button>
      <SecondComponent count={count}></SecondComponent>
    </div>
  )
}
export default App

自定义 Hooks 返回数组

import { useState, useEffect } from 'react'
function useCustomHooks(defaultCount) {
  const [count, setcount] = useState(defaultCount)
  useEffect(() => {
    console.log('测试执行')
  }, [count])

  return [count, setcount]
}

export default useCustomHooks

自定义 Hooks 返回 jsx

  • CutomHooks
import React, { useState, useEffect } from 'react'
function useCustomHooks(defaultCount) {
  const [count, setcount] = useState(defaultCount)
  useEffect(() => {
    console.log('测试执行')
  }, [count])
  function handleClick() {
    setcount(() => {
      return count + 1
    })
  }
  return (
    <div>
      <span>{count}</span>
      <button onClick={handleClick}>点击</button>
    </div>
  )
}

export default useCustomHooks
  • 父组件
import React from 'react'
import UseHooks from './CutomHooks'
function App() {
  return <div>{UseHooks(0)}</div>
}
export default App

文章作者: 雾烟云
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 雾烟云 !
  目录