css - 为 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中定义的类动态应用于页面中所述类的使用?
解决方案
JSX 样式属性接受包含 CSS 属性和值的 json 对象。
通常你会像这样传递类名和属性
<div style={{myStyles}}) className="ticss-0fcb86c1"/>
样式是 JSON 的地方写成
const mystyle = {
backgroundColor: "#ddd",
fontSize: "2em",
padding: "50px",
};
注意
样式名称从背景颜色转换为背景颜色,字体大小写为 fontSize 等等。
类被指定为“类名”
单个 html 元素被分配一个类。
您收到错误,因为样式变量是字符串,而不是 JSON 对象。
您可以尝试查看所有单独的 html 元素并添加样式,但我不建议这样做。
推荐阅读
- java - 从具有依赖关系的 jar 文件创建 docker 容器
- python - 如何用随机数制作函数
- java - driver.get(url) 与 driver.navigate().to(url);
- javascript - 引导多个文件选择 - 仅显示第一个文件
- haskell - 如何从 testDatabase 中删除 [ ]
- go - 如何检查函数参数和类型
- c++ - 与传统头文件相比,c++20 中的模块会减少编译时间吗?
- python - 如何解决“无法从'figures'导入名称'plot_2d_separator'”错误?
- javascript - Vanilla JS 滑动功能现在覆盖链接/预期行为
- bash - 从从标准输入接收到的 shell 脚本中提取二进制有效负载