当前位置:首页 > React

react实现点赞

2026-01-27 07:29:35React

React 实现点赞功能

在 React 中实现点赞功能通常涉及状态管理、事件处理和 UI 更新。以下是几种常见的实现方式:

使用 useState 管理点赞状态

import React, { useState } from 'react';

function LikeButton() {
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(0);

  const handleLike = () => {
    setLiked(!liked);
    setLikeCount(liked ? likeCount - 1 : likeCount + 1);
  };

  return (
    <div>
      <button onClick={handleLike}>
        {liked ? 'Unlike' : 'Like'}
      </button>
      <span>{likeCount} likes</span>
    </div>
  );
}

使用 useReducer 管理复杂状态

当点赞逻辑更复杂时,可以使用 useReducer:

import React, { useReducer } from 'react';

function likeReducer(state, action) {
  switch (action.type) {
    case 'TOGGLE_LIKE':
      return {
        ...state,
        liked: !state.liked,
        likeCount: state.liked ? state.likeCount - 1 : state.likeCount + 1
      };
    default:
      return state;
  }
}

function LikeButton() {
  const [state, dispatch] = useReducer(likeReducer, {
    liked: false,
    likeCount: 0
  });

  return (
    <div>
      <button onClick={() => dispatch({ type: 'TOGGLE_LIKE' })}>
        {state.liked ? 'Unlike' : 'Like'}
      </button>
      <span>{state.likeCount} likes</span>
    </div>
  );
}

结合后端 API 调用

实际应用中通常需要将点赞状态保存到后端:

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function LikeButton({ postId }) {
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(0);

  useEffect(() => {
    const fetchLikeStatus = async () => {
      const response = await axios.get(`/api/posts/${postId}/likes`);
      setLiked(response.data.liked);
      setLikeCount(response.data.likeCount);
    };
    fetchLikeStatus();
  }, [postId]);

  const handleLike = async () => {
    try {
      if (liked) {
        await axios.delete(`/api/posts/${postId}/likes`);
        setLikeCount(likeCount - 1);
      } else {
        await axios.post(`/api/posts/${postId}/likes`);
        setLikeCount(likeCount + 1);
      }
      setLiked(!liked);
    } catch (error) {
      console.error('Error updating like:', error);
    }
  };

  return (
    <div>
      <button onClick={handleLike}>
        {liked ? 'Unlike' : 'Like'}
      </button>
      <span>{likeCount} likes</span>
    </div>
  );
}

添加动画效果

可以使用 CSS 或动画库增强用户体验:

import React, { useState } from 'react';
import './LikeButton.css';

function LikeButton() {
  const [liked, setLiked] = useState(false);
  const [animating, setAnimating] = useState(false);

  const handleLike = () => {
    setLiked(!liked);
    setAnimating(true);
    setTimeout(() => setAnimating(false), 1000);
  };

  return (
    <div>
      <button 
        onClick={handleLike}
        className={`like-button ${liked ? 'liked' : ''} ${animating ? 'animate' : ''}`}
      >
        {liked ? '❤️' : '♡'}
      </button>
    </div>
  );
}

配套 CSS:

.like-button {
  transition: all 0.3s ease;
  font-size: 24px;
  background: none;
  border: none;
  cursor: pointer;
}

.like-button.liked {
  color: red;
}

.like-button.animate {
  transform: scale(1.2);
}

防抖处理

防止用户快速多次点击:

import React, { useState } from 'react';
import { debounce } from 'lodash';

function LikeButton() {
  const [liked, setLiked] = useState(false);

  const debouncedHandleLike = debounce(() => {
    setLiked(!liked);
  }, 300);

  return (
    <div>
      <button onClick={debouncedHandleLike}>
        {liked ? 'Unlike' : 'Like'}
      </button>
    </div>
  );
}

这些方法可以根据具体需求组合使用,构建出适合项目的点赞功能。

react实现点赞

标签: react
分享给朋友:

相关文章

react如何测试

react如何测试

React 测试方法 React 应用的测试通常涉及组件测试、集成测试和端到端测试。以下是常用的测试工具和方法: Jest Jest 是 Facebook 开发的 JavaScript 测试框架,适…

react native如何启动

react native如何启动

如何启动 React Native 项目 安装 Node.js 和 npm 确保已安装 Node.js(建议版本 16 或更高)和 npm(Node.js 自带)。可通过以下命令检查版本: nod…

如何评价react native

如何评价react native

React Native 的优势 跨平台开发效率高:基于 JavaScript 和 React 语法,可同时开发 iOS 和 Android 应用,减少重复代码量。性能接近原生:通过原生组件渲染,性能…

react 如何执行

react 如何执行

安装 Node.js 和 npm React 开发需要 Node.js 环境,因为它提供了 npm(或 yarn)包管理工具。从 Node.js 官网 下载并安装最新 LTS 版本。安装完成后,在终端…

如何记忆react

如何记忆react

理解核心概念 React的核心概念包括组件、状态(state)、属性(props)、生命周期方法(类组件)和钩子(函数组件)。掌握这些基础概念是记忆React的关键。组件是React应用的构建块,分为…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官…