您正在查看静态缓存页面 · 查看完整动态版本 · 登录 参与讨论

@wordpress/element 详解

✨步子哥 (steper) 2025年10月02日 23:56 0 次浏览

@wordpress/element 是 WordPress 官方提供的轻量级 React 抽象层,专门为 WordPress 区块编辑器(Gutenberg)和其他 WordPress JavaScript 应用设计。它提供 React 的核心功能,同时深度集成 WordPress 生态系统。

核心功能

1. React Hooks 支持

useState - 状态管理

import { useState } from '@wordpress/element';

const [state, setState] = useState(initialValue);

在 ActivityPub 项目中的使用示例:

// 反应区块的状态管理
const [isOpen, setIsOpen] = useState(false);
const [buttonRef, setButtonRef] = useState(null);

// 关注者区块的状态管理
const [followers, setFollowers] = useState([]);
const [loading, setLoading] = useState(true);

useEffect - 副作用处理

import { useEffect } from '@wordpress/element';

useEffect(() => {
  // 副作用逻辑
  return () => {
    // 清理逻辑
  };
}, [dependencies]);

在 ActivityPub 项目中的使用示例:

// 数据获取副作用
useEffect(() => {
  if (providedReactions) {
    setReactions(providedReactions);
    setLoading(false);
    return;
  }

  if (!postId || typeof postId !== 'number') {
    onError();
    return;
  }

  setLoading(true);
  apiFetch({
    path: `/${namespace}/posts/${postId}/reactions`,
  })
    .then((response) => {
      // 处理响应数据
      setReactions(response);
      setLoading(false);
    })
    .catch(onError);
}, [postId, providedReactions, fallbackReactions, namespace]);

useRef - DOM 引用

import { useRef } from '@wordpress/element';

const ref = useRef(initialValue);

在 ActivityPub 项目中的使用示例:

// 容器引用用于弹出层定位
const containerRef = useRef(null);

useMemo - 记忆化计算

import { useMemo } from '@wordpress/element';

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

2. JSX 渲染支持

@wordpress/element 提供完整的 JSX 语法支持,与 WordPress 组件系统无缝集成:

import { useState } from '@wordpress/element';
import { Button, Popover } from '@wordpress/components';

const ReactionGroup = ({ items, label }) => {
  const [isOpen, setIsOpen] = useState(false);
  
  return (
    <div className="reaction-group">
      <Button
        className="reaction-label is-link"
        onClick={() => setIsOpen(!isOpen)}
        aria-expanded={isOpen}
      >
        {label}
      </Button>
      {isOpen && (
        <Popover onClose={() => setIsOpen(false)}>
          {/* 弹出内容 */}
        </Popover>
      )}
    </div>
  );
};

3. 工具函数

createInterpolateElement - 创建带插值的 React 元素

这个函数专门用于处理包含 HTML 标签的翻译字符串:

import { createInterpolateElement } from '@wordpress/element';
import { __ } from '@wordpress/i18n';

const text = __(
  'This <strong>Follow Me</strong> block will adapt to the page it is on.',
  'activitypub'
);

const element = createInterpolateElement(text, { 
  strong: <strong /> 
});

在 ActivityPub 项目中的实际应用:

// src/shared/inherit-block-fallback.js
const text = sprintf(
  __(
    'This <strong>%1$s</strong> block will adapt to the page it is on...',
    'activitypub'
  ),
  name
);

return (
  <Card>
    <CardBody>{createInterpolateElement(text, { strong: <strong /> })}</CardBody>
  </Card>
);

设计目的和优势

1. 依赖管理

  • 版本控制: 避免直接依赖 React,便于 WordPress 核心统一管理 React 版本
  • 稳定性: 提供稳定的 API 接口,即使底层 React 版本升级也不会破坏现有代码
  • 兼容性: 确保与 WordPress 核心和其他插件的兼容性

2. WordPress 深度集成

  • 组件系统: 与 @wordpress/components 无缝集成
  • 国际化: 内置支持 @wordpress/i18n 系统
  • 数据管理: 与 @wordpress/data 状态管理集成
  • API 交互: 与 @wordpress/api-fetch 配合使用

3. 性能优化

  • 轻量级: 只包含必要的 React 功能,减少包大小
  • 针对性优化: 针对 WordPress 使用场景进行性能优化
  • 树摇优化: 支持现代打包工具的树摇优化

在 ActivityPub 项目中的具体应用

1. 状态管理

关注者区块 (src/followers/edit.js):

import { useState, useEffect } from '@wordpress/element';

const Edit = ({ attributes, setAttributes }) => {
  const [followers, setFollowers] = useState([]);
  const [loading, setLoading] = useState(true);
  
  // 状态管理逻辑...
};

2. 副作用处理

反应区块 (src/reactions/reactions.js):

useEffect(() => {
  if (providedReactions) {
    setReactions(providedReactions);
    setLoading(false);
    return;
  }
  
  // 异步数据获取逻辑
  apiFetch({
    path: `/${namespace}/posts/${postId}/reactions`,
  })
    .then(setReactions)
    .catch(onError);
}, [postId, providedReactions]);

3. 用户交互

关注我区块 (src/follow-me/edit.js):

import { useEffect, useState } from '@wordpress/element';

const Edit = ({ attributes, setAttributes }) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  
  const openModal = () => setIsModalOpen(true);
  const closeModal = () => setIsModalOpen(false);
  
  // 模态框交互逻辑...
};

4. 国际化插值

继承模式回退组件 (src/shared/inherit-block-fallback.js):

import { createInterpolateElement } from '@wordpress/element';
import { sprintf, __ } from '@wordpress/i18n';

const text = sprintf(
  __(
    'This <strong>%1$s</strong> block will adapt to the page it is on...',
    'activitypub'
  ),
  name
);

return createInterpolateElement(text, { strong: <strong /> });

与原生 React 的对比

特性@wordpress/element原生 React
**依赖管理**WordPress 包管理直接依赖 React
**集成度**深度集成 WordPress 生态系统通用 React 应用
**国际化**内置 WordPress i18n 支持需要额外配置
**组件系统**优先使用 WordPress 组件通用 React 组件
**版本控制**WordPress 核心统一管理项目自行管理
**兼容性**确保 WordPress 插件兼容性依赖项目配置

最佳实践

1. 导入规范

// 推荐:按需导入
import { useState, useEffect, useRef } from '@wordpress/element';

// 不推荐:全部导入
import * as Element from '@wordpress/element';

2. Hook 使用

// 推荐:清晰的依赖数组
useEffect(() => {
  // 副作用逻辑
}, [userId, postId]);

// 不推荐:缺少依赖或依赖不完整
useEffect(() => {
  // 副作用逻辑
}, []);

3. 状态设计

// 推荐:相关状态分组
const [userData, setUserData] = useState({
  followers: [],
  following: [],
  loading: true
});

// 不推荐:分散的状态
const [followers, setFollowers] = useState([]);
const [following, setFollowing] = useState([]);
const [loading, setLoading] = useState(true);

总结

@wordpress/element 是 WordPress 现代 JavaScript 开发的核心基础,它:

  1. 提供 React 核心功能 - Hooks、JSX、组件渲染
  2. 深度集成 WordPress - 与 WordPress 组件、国际化、数据管理无缝集成
  3. 优化依赖管理 - 避免直接依赖 React,便于版本控制和兼容性
  4. 支持现代开发模式 - 函数式组件、Hooks、状态管理
在 ActivityPub 项目中,@wordpress/element 被广泛用于构建交互式的前端区块组件,提供现代化的用户体验,同时确保与 WordPress 生态系统的完美兼容。

讨论回复

1 条回复
✨步子哥 (steper) #1
10-03 00:14

本质上就是改进了React诸多不便并深度集成,更重要的是去掉了对React对直接依赖。