块编辑器开发文档

WithFallbackStyles

💡 云策文档标注

概述

本文档介绍了 WordPress 组件库中的 withFallbackStyles 高阶组件,用于在 React 组件中获取并传递回退样式值,如背景色和文本颜色,以增强样式处理能力。

关键要点

  • withFallbackStyles 是一个高阶组件,允许从 DOM 节点计算样式并作为 props 传递给子组件。
  • 使用示例展示了如何通过 getComputedStyle 获取按钮的背景色和文本颜色,并在组件中显示这些值。
  • 适用于需要动态获取或回退样式的 WordPress 开发场景,提升组件样式灵活性。

代码示例

import { withFallbackStyles, Button } from '@wordpress/components';

const { getComputedStyle } = window;

const MyComponentWithFallbackStyles = withFallbackStyles(
    ( node, ownProps ) => {
        const buttonNode = node.querySelector( 'button' );
        return {
            fallbackBackgroundColor: getComputedStyle( buttonNode )
                .backgroundColor,
            fallbackTextColor: getComputedStyle( buttonNode ).color,
        };
    }
)( ( { fallbackTextColor, fallbackBackgroundColor } ) => (
    <div>
        <Button variant="primary">My button</Button>
        <div>Text color: { fallbackTextColor }</div>
        <div>Background color: { fallbackBackgroundColor }</div>
    </div>
) );

📄 原文内容

Usage

import { withFallbackStyles, Button } from '@wordpress/components';

const { getComputedStyle } = window;

const MyComponentWithFallbackStyles = withFallbackStyles(
    ( node, ownProps ) => {
        const buttonNode = node.querySelector( 'button' );
        return {
            fallbackBackgroundColor: getComputedStyle( buttonNode )
                .backgroundColor,
            fallbackTextColor: getComputedStyle( buttonNode ).color,
        };
    }
)( ( { fallbackTextColor, fallbackBackgroundColor } ) => (
    <div>
        <Button variant="primary">My button</Button>
        <div>Text color: { fallbackTextColor }</div>
        <div>Background color: { fallbackBackgroundColor }</div>
    </div>
) );