当前位置:首页 > React

react点赞实现

2026-01-26 18:43:43React

react点赞实现

实现React点赞功能

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

使用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
分享给朋友:

相关文章

react native 如何

react native 如何

安装 React Native 开发环境 确保系统已安装 Node.js(建议版本 16 或更高)。通过以下命令安装 React Native CLI 工具: npm install -g reac…

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment 包。确保项目中已安装 moment.js,因为 react-moment 依赖它。 npm instal…

react如何开发组件

react如何开发组件

React 组件开发基础 React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。 函数组件示例: function Gr…

react如何查

react如何查

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

react架构如何

react架构如何

React 架构核心概念 React 的架构围绕组件化、虚拟 DOM 和单向数据流设计。组件是构建用户界面的独立模块,分为函数组件和类组件。虚拟 DOM 通过高效的 Diff 算法减少直接操作真实 D…

react如何读

react如何读

React 的发音 React 的发音为 /riˈækt/(音标),读作“瑞-艾克特”。其中: “Re” 发音类似英文单词 “read” 的开头部分。 “act” 发音与英文单词 “act” 一致…