useState
是React Hooks中的一个非常重要的hook,它允许函数组件拥有并更新状态,在typescript中使用useState,需要确保变量的类型被正确声明。
基本用法
useState接收一个初始值,并返回一个状态变量和一个更新该状态的函数,这里是一个简单的例子
import React,{useState} from 'react'
const Counter:React.FC=()=>{
const [count,setCount] = useState(0);//初始值为0
const increment = ()=>{
setcount(count+1);
}
return (
<div>
<p>you click{count}</p>
<button onClick={increment}>click me</button>
</div>
)
}
export default Counterl
显式类型声明
显式指定状态变量的类型
import React,{useState} from 'react'
interface CounterProps {
initialCount: number;
}
const Counter:React.FC<CountProps> = (initialCount) =>{
const [count,setCount] = useState<number>(initialCount) //显式声明
const increment = ()=>{
setCount(count+1)
}
return (
<div>
<p> you click {count}</p>
<button onClick={increment}>click me</button>
)
}
推断类型
如果初始值提供了足够的信息类型,Typescript通常可以自动推断状态变量的类型
import React, {useState} from 'react'
interface CounterProps{
initialCount:number;
}
const Counter:React.FC<CountProps> =({initialCount})=>{
const [count,setCount] = useState(initialCount) //类型推断
const increment = () => {
setCount(count+1)
}
return (
<div>
<p>You clicked {count} times</p>
<button onClick={increment}>Click me</button>
</div>
);
}
export default Counter;
示例:购物车组件
import React, { useState } from 'react';
// 定义类型
interface Product {
id: number;
name: string;
price: number;
}
interface CartItem extends Product {
quantity: number;
}
interface ShoppingCartState {
cartItems: CartItem[];
}
interface ShoppingCartProps {
products: Product[];
}
const ShoppingCart: React.FC<ShoppingCartProps> = ({ products }) => {
const [cartItems, setCartItems] = useState<CartItem[]>([]);
const addToCart = (product: Product) => {
const itemIndex = cartItems.findIndex((item) => item.id === product.id);
if (itemIndex === -1) {
setCartItems([...cartItems, { ...product, quantity: 1 }]);
} else {
const updatedItems = [...cartItems];
updatedItems[itemIndex].quantity += 1;
setCartItems(updatedItems);
}
};
const updateQuantity = (productId: number, delta: number) => {
const itemIndex = cartItems.findIndex((item) => item.id === productId);
if (itemIndex !== -1) {
const updatedItems = [...cartItems];
const newQuantity = updatedItems[itemIndex].quantity + delta;
if (newQuantity > 0) {
updatedItems[itemIndex].quantity = newQuantity;
} else {
updatedItems.splice(itemIndex, 1);
}
setCartItems(updatedItems);
}
};
const getTotalPrice = () => {
return cartItems.reduce((total, item) => total + item.price * item.quantity, 0);
};
return (
<div>
<h2>Product List</h2>
<ul>
{products.map((product) => (
<li key={product.id}>
<span>{product.name}</span>
<span>{product.price.toFixed(2)}</span>
<button onClick={() => addToCart(product)}>Add to Cart</button>
</li>
))}
</ul>
<h2>Shopping Cart</h2>
<ul>
{cartItems.map((item) => (
<li key={item.id}>
<span>{item.name}</span>
<span>{item.quantity}</span>
<button onClick={() => updateQuantity(item.id, -1)}>-</button>
<button onClick={() => updateQuantity(item.id, 1)}>+</button>
<span>{(item.price * item.quantity).toFixed(2)}</span>
</li>
))}
</ul>
<p>Total Price: {getTotalPrice().toFixed(2)}</p>
</div>
);
};
export default ShoppingCart;
在这个示例中,我们使用 useState 来管理购物车中的商品。addToCart 函数用于将商品添加到购物车中,updateQuantity 函数用于更新购物车中商品的数量,getTotalPrice 函数用于计算购物车的总价。