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

发布时间:2024年01月11日

?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>
  );
}

文章来源:https://blog.csdn.net/qq_43491495/article/details/135532810
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。