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

react实现点赞

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 或动画库增强用户体验:

react实现点赞

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 native 如何

react native 如何

React Native 开发基础 React Native 是一个用于构建跨平台移动应用的框架,允许开发者使用 JavaScript 和 React 编写代码,同时生成原生 iOS 和 Androi…

react如何重置

react如何重置

重置 React 应用的状态 使用 useState 钩子重新初始化状态变量是最直接的方法。将状态变量重置为初始值或空值即可完成重置。 const [count, setCount] = useSt…

如何恢复react

如何恢复react

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

react如何引入

react如何引入

引入React的方法 React可以通过多种方式引入项目,具体取决于项目需求和开发环境。以下是常见的几种方法: 通过CDN引入 在HTML文件中直接通过CDN链接引入React和ReactDOM:…

react 如何操作cookie

react 如何操作cookie

安装依赖 在React项目中操作cookie通常需要第三方库的支持,推荐使用js-cookie。通过npm或yarn安装: npm install js-cookie # 或 yarn add js…

react如何代码优化

react如何代码优化

减少不必要的重新渲染 使用 React.memo 包装函数组件以避免在 props 未变化时重新渲染。对于类组件,可以通过 shouldComponentUpdate 或继承 PureComponen…