当前位置:首页 > 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);
}

防抖处理

防止用户快速多次点击:

react实现点赞

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中验证表单数据通常使用以下几种方式: 内置HTML5验证 利用HTML5原生表单验证属性如required、pattern等,结合form.noValidate属性禁用浏览…

如何配置react

如何配置react

配置React项目的步骤 安装Node.js和npm 确保系统已安装Node.js(包含npm)。可通过官网下载并安装最新版本。安装完成后,运行以下命令验证版本: node -v npm -v 创建…

如何用react

如何用react

使用React的基本步骤 安装Node.js和npm 确保系统已安装Node.js和npm。Node.js自带npm,可从官网下载安装包。安装完成后,通过命令行验证版本: node -v npm -…

react如何发布

react如何发布

发布React应用的步骤 构建生产版本 使用以下命令生成优化后的生产版本代码,代码会被压缩并移除开发环境中的调试工具: npm run build 构建完成后会生成build文件夹,包含所有静态资源…

react 如何循环

react 如何循环

循环渲染列表 在React中,循环渲染列表通常使用map方法。map可以遍历数组并返回一个新的React元素数组。 const items = ['Apple', 'Banana', 'Orange…

如何恢复react

如何恢复react

恢复 React 项目的方法 检查并修复依赖项 运行 npm install 或 yarn install 重新安装所有依赖项。如果依赖项损坏或缺失,这将恢复项目所需的库和工具。 恢复删除的文件 如…