React 与 TS 结合使用 Hook 总结

news/2024/7/15 17:03:48 标签: react.js, 前端, 学习, 笔记

学习 React 时,我们总会遇到在 TS 和 JS 之间切换来开发多个项目,而有时会忘记 TS 的语法,所以编写一下 React 结合 TS 开发时的一些总结知识点,以便后续回顾用。

**说明:**这只是总结 React 与 TS 结合使用时的写法回顾,并不是介绍钩子函数的使用。

使用 userState

这节主要是回顾 useState 钩子函数的 TS 的写法。实例如下:

type AuthUserProp = {
  name: string;
  email: string;
};

const UseStartProps: React.FC = () => {
  const [authUser, setAuthUser] = useState<AuthUserProp | null>(null);
  const [isLogin, setIsLogin] = useState<boolean>(false);

  return (
    <div>
      <h2>useStart 使用实例</h2>
      <button
        onClick={() => {
          setIsLogin(true);
          setAuthUser({ name: "Tom", email: "tom@example.com" });
        }}
      >
        登录
      </button>
      <button
        onClick={() => {
          setIsLogin(false);
          setAuthUser(null);
        }}
      >
        登出
      </button>
      {isLogin ? (
        <div>
          <p>{authUser?.name}</p>
          <p>{authUser?.email}</p>
        </div>
      ) : (
        <div>还未登录</div>
      )}
    </div>
  );
};

export default UseStartProps;

使用 useReducer

这节主要是回顾 useReducer 钩子函数的 TS 写法,以及 TS 联合类型 使用方式。实例如下:

type CounterState = {
  count: number;
};

type UpdateAction = {
  type: "increment" | "decrement";
  payload: number;
};

type ResetAction = {
  type: "reset";
};

type CounterAction = UpdateAction | ResetAction; // 因为重置操作并不需要type这个参数,所以通过TS的类型推导来做判断

const UseReducerProps: React.FC = () => {
  const initialState = { count: 0 };

  function reducer(state: CounterState, action: CounterAction) {
    switch (action.type) {
      case "increment":
        return { count: state.count + action.payload };
      case "decrement":
        return { count: state.count - action.payload };
      case "reset":
        return initialState;
      default:
        return state;
    }
  }

  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <h2>useReducer 使用实例</h2>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "increment", payload: 10 })}>
        添加 10
      </button>
      <button onClick={() => dispatch({ type: "decrement", payload: 10 })}>
        减去 10
      </button>
      <button onClick={() => dispatch({ type: "reset" })}>重置</button>
    </div>
  );
};

export default UseReducerProps;

使用 useContext

这节主要是回顾 useContext 钩子函数的 TS 写法,以及 useContext 于 useStart 钩子函数使用时的写法。实例如下:

  • userContext 钩子函数使用
// ThemeContext.tsx
type ThemeContextProviderProps = {
  children: React.ReactNode;
};

export const ThemeContext = createContext(theme);

export const ThemeContextProvider = ({
  children,
}: ThemeContextProviderProps) => {
  return (
    <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>
  );
};

// Box.tsx
const Box: React.FC = () => {
  const theme = useContext(ThemeContext);

  return (
    <div
      style={{
        backgroundColor: theme.secondary.main,
        color: theme.secondary.text,
      }}
    >
      Theme context
    </div>
  );
};

export default Box;
  • useContext 和 useStart 钩子函数使用
// UserContext.tsx
type AuthUser = {
  name: string;
  email: string;
};

type UserContextType = {
  user: AuthUser | null;
  setUser: React.Dispatch<React.SetStateAction<AuthUser | null>>;
};

type UserContextProviderProps = {
  children: React.ReactNode;
};

// 这里可以写成 export const UserContext = createContext({} as UserContextType),但是不建议这这样,这样做不好判断context的值是否为空
export const UserContext = createContext<UserContextType | null>(null);

export const UserContextProvider = ({ children }: UserContextProviderProps) => {
  const [user, setUser] = useState<AuthUser | null>(null);

  return (
    <UserContext.Provider value={{ user: user, setUser: setUser }}>
      {children}
    </UserContext.Provider>
  );
};

// User.tsx
export const User = () => {
  const userContext = useContext(UserContext);

  const handleLogin = () => {
    userContext?.setUser({
      name: "Vishwas",
      email: "asd@asd.com",
    });
  };

  const handleLogout = () => {
    userContext?.setUser(null);
  };
  return (
    <div>
      <button onClick={handleLogin}>Login</button>
      <button onClick={handleLogout}>Logout</button>
      <div>用户名: {userContext?.user?.name}</div>
      <div>用户邮箱: {userContext?.user?.email}</div>
    </div>
  );
};

使用 useRef

这节主要是回顾 useRef 钩子函数的 TS 写法。实例如下:

  • DOM 元素
export const DomRef = () => {
  const inputRef = useRef<HTMLInputElement>(null!);
  useEffect(() => {
    inputRef.current.focus();
  }, []);
  return (
    <div>
      <input type="text" ref={inputRef} />
    </div>
  );
};
  • 可变 ref(setTimeout 为例)
export const MutableRef = () => {
  const [timer, setTimer] = useState(0);
  const interValRef = useRef<number | null>(null);

  const stopTimer = () => {
    if (interValRef.current) {
      window.clearInterval(interValRef.current);
    }
  };
  useEffect(() => {
    interValRef.current = window.setInterval(() => {
      setTimer((timer) => timer + 1);
    }, 1000);
    return () => {
      stopTimer();
    };
  }, []);

  return (
    <div>
      HookTimer - {timer} -
      <button onClick={() => stopTimer()}>Stop Timer</button>
    </div>
  );
};

http://www.niftyadmin.cn/n/5014986.html

相关文章

01_前端css编写的三种方式

前言 CSS的引入方式共有三种&#xff1a;行内样式、内部样式表、外部样式表 一、内联式引入 用法&#xff1a; 在元素上直接通过style属性进行设置css样式设置 示例&#xff1a; <h1 style"color:red;">style属性的应用</h1> <p style"font-si…

Android相机-架构3

目录 引言 1. Android相机的整体架构 2. 相机 HAL 2.1 AIDL相机HAL 2.2 相机 HAL3 功能 3. HAL子系统 3.1 请求 3.2 HAL和相机子系统 3.2.1 相机的管道 3.2.2 使用 Android Camera API 的步骤 3.2.3 HAL 操作摘要 3.3 启动和预期操作顺序 3.3.1 枚举、打开相机设备…

【GO语言基础】控制流

系列文章目录 【Go语言学习】ide安装与配置 【GO语言基础】前言 【GO语言基础】变量常量 【GO语言基础】数据类型 【GO语言基础】控制流 文章目录 系列文章目录条件语句if-else 结构判断一个字符串是否为空&#xff1a;switch结构 循环结构for 循环&#xff08;C风格&#xff…

无涯教程-JavaScript - IMSUM函数

描述 IMSUM函数以x yi或x yj文本格式返回两个或多个复数的和。当添加复数时,实数和虚数系数分别相加,即找到两个复数a bi和c di的和的方程为- (a bi)(c in)(a c)(b d)我 语法 IMSUM (inumber1, [inumber2] ...)争论 Argument描述Required/OptionalInumber11 to 25…

C++String模拟实现

实际上string没什么可讲&#xff0c;主要是对string函数的运用与理解&#xff0c;与其写库函数如何用&#xff0c;不如直接去看c库函数来得好。 以下是自己实现string功能函数。但没对string库中的全部函数进行实现&#xff0c;而是实现主要使用的。 .cpp内是用来测试函数功能…

xCode14.3.1运行MonkeyDev出现“Executable Not Found“的解决办法

安装MonkeyDev遇到的坑 环境&#xff1a;Xcode Version 14.3.1 (14E300c) 错误提示 is not a valid path to an executable file. 报错 /Users/xxxx//Library/Developer/Xcode/DerivedData/MonTest-ccparhdyzjuqhjdergwrngpfwwoh/Build/Products/Debug-iphoneos/MonTest.app…

糖生物学要点.4- 学习指南

学习指南 转到&#xff1a; 第1章 历史背景与概述 哪些因素阻碍了聚糖生物学&#xff08;“糖生物学”&#xff09;研究与传统分子和细胞生物学的整合&#xff1f; 为什么进化反复选择聚糖作为所有细胞表面的主要分子&#xff1f; 解释细胞外聚糖和核/胞质聚糖之间的区别。 影响…

【可定制、转换时间戳】解析nc文件,并保存为csv文件

解析nc文件&#xff0c;并保存为csv文件 写在最前面解析nc文件&#xff08;代码汇总放最后面&#xff09;读取nc文件获取气象文件中所有变量解析时间解析部分代码汇总 写入csv文件 写在最前面 愿称之为&#xff1a;支持私人订制、非常完美的版本 参考&#xff1a; 解析部分参…