React---函数组件的常用hook

 1. useState

import { useState } from 'react';

interface State {
  count: number;
}

function Counter() {
  const [state, setState] = useState<State>({ count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>
    </div>
  );
}

 2. useEffect

import { useEffect, useState } from 'react';

function DataFetcher() {
  const [data, setData] = useState<string | null>(null);

  useEffect(() => {
    // 模拟数据获取
    setTimeout(() => {
      setData('Fetched data!');
    }, 1000);
  }, []); // 空数组表示只在组件挂载时运行

  return (
    <div>
      <p>Data: {data}</p>
    </div>
  );
}

3. useContext 

import { createContext, useContext } from 'react';

interface ContextValue {
  value: string;
}

const MyContext = createContext<ContextValue>({ value: 'Default Context Value' });

function ContextConsumer() {
  const contextValue = useContext(MyContext);

  return (
    <div>
      <p>Context Value: {contextValue.value}</p>
    </div>
  );
}

4. useReducer 

import { useReducer } from 'react';

interface State {
  count: number;
}

type Action = { type: 'increment' };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    default:
      return state;
  }
}

function ReducerExample() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
    </div>
  );
}

5. useCallback 

import { useCallback, useState } from 'react';

function CallbackExample() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

6. useMemo 

import { useMemo, useState } from 'react';

function MemoExample() {
  const [a, setA] = useState(1);
  const [b, setB] = useState(2);

  const result = useMemo(() => {
    console.log('Computing result...');
    return a + b;
  }, [a, b]);

  return (
    <div>
      <p>Result: {result}</p>
      <button onClick={() => { setA(a + 1); }}>Increment A</button>
      <button onClick={() => { setB(b + 1); }}>Increment B</button>
    </div>
  );
}

7. useEffect 

import { useEffect, useRef } from 'react';

function RefExample() {
  const inputRef = useRef<HTMLInputElement | null>(null);

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return (
    <div>
      <input ref={inputRef} type="text" />
    </div>
  );
}

8. useImperativeHandle 

import { forwardRef, useImperativeHandle, useRef } from 'react';

interface MyComponentProps {
  // Props definition
}

interface MyComponentMethods {
  focus: () => void;
  // Other exposed methods
}

const MyComponent = forwardRef<MyComponentMethods, MyComponentProps>((props, ref) => {
  const internalRef = useRef<HTMLInputElement | null>(null);

  useImperativeHandle(ref, () => ({
    focus: () => {
      if (internalRef.current) {
        internalRef.current.focus();
      }
    },
    // Other exposed methods or values
  }), []);

  return (
    <div>
      <input ref={internalRef} type="text" />
    </div>
  );
});

// Usage
function ImperativeHandleExample() {
  const myRef = useRef<MyComponentMethods>(null);

  useEffect(() => {
    if (myRef.current) {
      myRef.current.focus();
    }
  }, []);

  return (
    <div>
      <MyComponent ref={myRef} />
    </div>
  );
}

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值