@wordpress/element 是 WordPress 官方提供的轻量级 React 抽象层,专门为 WordPress 区块编辑器(Gutenberg)和其他 WordPress JavaScript 应用设计。它提供 React 的核心功能,同时深度集成 WordPress 生态系统。
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);
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]);
import { useRef } from '@wordpress/element';
const ref = useRef(initialValue);
在 ActivityPub 项目中的使用示例:
// 容器引用用于弹出层定位
const containerRef = useRef(null);
import { useMemo } from '@wordpress/element';
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
@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>
);
};
这个函数专门用于处理包含 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>
);
@wordpress/components 无缝集成@wordpress/i18n 系统@wordpress/data 状态管理集成@wordpress/api-fetch 配合使用关注者区块 (src/followers/edit.js):
import { useState, useEffect } from '@wordpress/element';
const Edit = ({ attributes, setAttributes }) => {
const [followers, setFollowers] = useState([]);
const [loading, setLoading] = useState(true);
// 状态管理逻辑...
};
反应区块 (src/reactions/reactions.js):
useEffect(() => {
if (providedReactions) {
setReactions(providedReactions);
setLoading(false);
return;
}
// 异步数据获取逻辑
apiFetch({
path: `/${namespace}/posts/${postId}/reactions`,
})
.then(setReactions)
.catch(onError);
}, [postId, providedReactions]);
关注我区块 (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);
// 模态框交互逻辑...
};
继承模式回退组件 (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 /> });
| 特性 | @wordpress/element | 原生 React |
|---|---|---|
| **依赖管理** | WordPress 包管理 | 直接依赖 React |
| **集成度** | 深度集成 WordPress 生态系统 | 通用 React 应用 |
| **国际化** | 内置 WordPress i18n 支持 | 需要额外配置 |
| **组件系统** | 优先使用 WordPress 组件 | 通用 React 组件 |
| **版本控制** | WordPress 核心统一管理 | 项目自行管理 |
| **兼容性** | 确保 WordPress 插件兼容性 | 依赖项目配置 |
// 推荐:按需导入
import { useState, useEffect, useRef } from '@wordpress/element';
// 不推荐:全部导入
import * as Element from '@wordpress/element';
// 推荐:清晰的依赖数组
useEffect(() => {
// 副作用逻辑
}, [userId, postId]);
// 不推荐:缺少依赖或依赖不完整
useEffect(() => {
// 副作用逻辑
}, []);
// 推荐:相关状态分组
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 开发的核心基础,它:
@wordpress/element 被广泛用于构建交互式的前端区块组件,提供现代化的用户体验,同时确保与 WordPress 生态系统的完美兼容。