You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向网站添加React时如何将类组件转换为函数组件

实现方案

你无需修改index.html的代码,仅替换like_button.js的内容即可完成类组件转函数组件的改造,改造后的完整代码如下:

"use strict";

const e = React.createElement;

function LikeButton(props) {
  // 用useState Hook管理点赞状态
  const [liked, setLiked] = React.useState(false);

  return e(
    "button",
    {
      onClick: () => setLiked(prevState => !prevState)
    },
    liked ? "Liked " + props.commentID : "Unliked"
  );
}

document.querySelectorAll(".like_button_container").forEach((domContainer) => {
  const commentID = domContainer.dataset.commentid;
  ReactDOM.render(e(LikeButton, { commentID: commentID }), domContainer);
});

核心改动说明

  • 将原来的Class类声明改为普通函数声明,直接接收props作为入参,无需再通过this.props访问参数
  • 使用React内置的useState Hook实现状态管理,替代类组件中的constructor初始化状态和setState更新状态逻辑
  • 移除所有this关键字的使用,直接访问状态变量和props参数即可

内容的提问来源于stack exchange,提问作者Krushnasinh Jadeja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 02:24:03