首页 > 解决方案 > 为 Wordpress 的 REST API 应用自定义 CSS

问题描述

我有一个沿着这些方向的组件......

class AComponent extends React.Component {

state = {
    page: '',
    styleObj:{},
    isLoaded: false
};

componentDidMount = () => {
    this.getPageSegment();
}
...

其中函数getPageSegment()定义为

getPageSegment = async () => {
    let response = await axios({
        method: 'get',
        url: '<WORDPRESS-SERVER>/wp-json/wp/v2/posts/27'
    });
    let page = response.data.content.rendered;
    let styleObj = response.data.customCSS;
    this.setState({
        page: page,
        styleObj: styleObj,
        isLoaded: true
    });
};

渲染功能是这样的:

render() {
    if (this.state.isLoaded) {
        return (
            <div>
                <div dangerouslySetInnerHTML={{ __html: this.state.page }} style={this.state.styleObj} />
            </div>
        );
    } else {
        return '';
    }
}

我已经实现了一些 wordpress 逻辑,以根据此处的代码通过 REST 端点公开自定义 CSS

这是来自 wordpress REST 端点的响应:

[
    {
    ...
    "content":{
        "rendered":{
            "\n<p class=\"ticss-66b44f07\">111 Lorem ipsum dolor</p>\n\n\n\n<p class=\"ticss-4848221b\">222 Vivamus maximus</p>\n\n\n\n<figure class=\"wp-block-image size-large is-resized ticss-0fcb86c1\"><img loading=\"lazy\" src=\"https://i2.wp.com/www.downshiftology.com/wp-content/uploads/2019/04/Cobb-Salad-3.jpg\" alt=\"Image of cob salad. Bacon, geggs, avocado slices etc.\" width=\"512\" height=\"342\"/><figcaption>cob salad image</figcaption></figure>\n"
        }
    }
    ...
    "customCSS": ".ticss-66b44f07 {background: #999;} .ticss-4848221b {background: #ddd;  font-size:2rem;  padding: 50px;} .ticss-0fcb86c1 img {    border-radius: 10px;}",
    ...
    }
]

当我应用上述样式对象时,出现以下错误:

Error: The 'style' prop expects a mapping from style properties to values, not a string

我理解错误。当通过react呈现时,如何将customCSS中定义的类动态应用于页面中所述类的使用?

标签: cssreactjswordpress

解决方案


JSX 样式属性接受包含 CSS 属性和值的 json 对象。

通常你会像这样传递类名和属性

<div style={{myStyles}}) className="ticss-0fcb86c1"/>

样式是 JSON 的地方写成

const mystyle = {
      backgroundColor: "#ddd",
      fontSize: "2em",
      padding: "50px",
    };

注意

  • 样式名称从背景颜色转换为背景颜色,字体大小写为 fontSize 等等。

  • 类被指定为“类名”

  • 单个 html 元素被分配一个类。

您收到错误,因为样式变量是字符串,而不是 JSON 对象。

您可以尝试查看所有单独的 html 元素并添加样式,但我不建议这样做。


推荐阅读