当前位置:首页 > React

react点赞实现

2026-01-26 18:43:43React

react点赞实现

实现React点赞功能

使用React实现点赞功能可以通过状态管理、事件处理和UI反馈来完成。以下是几种常见的实现方式:

react点赞实现

使用useState管理点赞状态

import React, { useState } from 'react';

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

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

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

使用useReducer管理复杂状态

import React, { useReducer } from 'react';

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

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

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

添加动画效果

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

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

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

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

对应的CSS样式:

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

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

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

与后端API交互

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

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

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

  const handleLike = async () => {
    try {
      const response = liked
        ? await axios.delete(`/api/posts/${postId}/likes`)
        : await axios.post(`/api/posts/${postId}/likes`);

      setLiked(response.data.liked);
      setCount(response.data.count);
    } catch (error) {
      console.error('Error updating like:', error);
    }
  };

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

使用自定义Hook封装逻辑

import { useState } from 'react';

function useLike(initialLiked = false, initialCount = 0) {
  const [liked, setLiked] = useState(initialLiked);
  const [count, setCount] = useState(initialCount);

  const toggleLike = () => {
    setLiked(!liked);
    setCount(liked ? count - 1 : count + 1);
  };

  return { liked, count, toggleLike };
}

function LikeButton() {
  const { liked, count, toggleLike } = useLike();

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

以上实现方式可以根据具体需求选择使用,从简单的前端状态管理到与后端API交互的完整解决方案。

标签: react
分享给朋友:

相关文章

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取当前日期 在 React 中通过 Moment.js 获取当前日期,可以直接调用 moment() 函数。它会返回包含当前日期和时间的 Moment 对象。 impor…

react 如何执行

react 如何执行

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

如何记忆react

如何记忆react

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

如何改造react

如何改造react

改造 React 项目的关键方法 分析当前项目结构 通过评估现有组件、状态管理和依赖项,明确需要改进的部分。使用工具如 webpack-bundle-analyzer 识别性能瓶颈。 升级 Reac…

react如何查

react如何查

React 查询方法 React 提供了多种查询 DOM 元素的方式,以下是几种常见的方法: 使用 ref 通过 useRef 钩子可以获取 DOM 节点的引用,适用于直接操作 DOM 的场景。…

react如何encode

react如何encode

React 中编码的实现方式 在 React 中,编码通常涉及对 URL、HTML 实体或特殊字符的处理。以下是几种常见的编码方法: 使用 encodeURIComponent 进行 URL 编码…