React——hooks 钩子函数基本用法

【useState】声明 state 变量

useState 会返回一个数组:[当前状态,更新它的函数]

import { useState } from "react"

function Index() {
  const [num, setNum] = useState(0)

  return <div>
    <h1>计数器:{num}</h1>
    <button onClick={() => setNum(num + 1)}>增加</button>
  </div>
}
export default Index

【useEffect】副作用集合了(组件初始化、更新、销毁)

useEffect 可以接收两个参数

//组件会在初始化和更新的时候执行函数
useEffect(() => {
	console.log("useEffect-updata")
})
//组件会在销毁时执行return的函数
useEffect(() => {
	console.log("useEffect-updata")
	return ()=>{
		console.log("useEffect-destroy")
	}
})
//组件初始化时执行,只会执行一次
useEffect(() => {
	console.log("useEffect-updata")
},[])
//组件初始化时执行或者num变量发生改变时执行
useEffect(() => {
	console.log("useEffect-updata")
},[num])

【useContext】获取上下文

useContext 配合着 createContext 一起使用

//父组件
import { useState , createContext } from "react"
import A from "../../components/A/index"

export const C:any = createContext(null)

export const Index = () => {
  const [list] = useState([1, 2])

  return <C.Provider value={{list}}>
    <A></A>
  </C.Provider>
}
//子组件
import B from "../B/index"

export default function A(){
  return <div>
    <B></B>
  </div>
}
//孙组件
import { useContext } from "react"
import { C } from "../../view/PageFn/PageFn1"

export default function B(){
  const { list } = useContext(C)

  return <div>
    {list}
  </div>
}

【useReducer】useState 的替代方案

useReducer 接收三个参数(回调函数,变量,变量初始化函数)
useReducer 返回一个数组 [变量,执行函数]

import { useReducer } from "react"

const initData = "Hello"

export const Index = () => {
  const [state, dispatch] = useReducer(reducer,initData,initFn)

  return <div>
    <div>state:{state}</div>
    <button onClick={()=>dispatch("B")}>打招呼</button>
  </div>
}

/* state设置的变量,action传递的参数 */
function reducer(state: any, action: any) {
  return `${state} and ${action}`
}

/* state变量的初始化函数 */
function initFn(state: any){
  return `${state} A`
}

【useRef】获取dom

import { useRef } from "react"

export const Index = () => {
  const el = useRef<any>(null)

  const hanleGetEl = ()=>{
    console.log(el.current.focus())
  }

  return <div>
    <input type={"text"} ref={el} />
    <button onClick={hanleGetEl}>Focus El</button>
  </div>
}

【useImperativeHandle】配合forwardRef一起使用

useImperativeHandle 可以让你在使用 ref 时自定义暴露给父组件的实例值

import { forwardRef, useImperativeHandle, useRef } from "react"
//父组件
export const Index = () => {
  const AInput = forwardRef(A)
  const AInputRef = useRef<any>(null)
  //点击按钮执行子组件暴露的focus方法
  const handleFocus = ()=>{
    AInputRef.current.focus()
  }

  return <div>
    <AInput ref={AInputRef}></AInput>
    <button onClick={handleFocus}>Get El</button>
  </div>
}
//子组件
function A(_props:any,ref:any){
  const inputRef = useRef<any>(null)
  useImperativeHandle(ref,()=>({
    focus:()=>{
      inputRef.current.focus()
    }
  }))
  return <input type="text" ref={inputRef} />
}

你可能感兴趣的:(React,react.js,javascript,前端)