首页 > 解决方案 > 将所有 html 样式属性替换为 React 兼容样式

问题描述

我目前正在迁移我的博客,并希望将我的 html 中的所有样式属性替换为与 React 兼容的属性。

例如

<div style="display: flex; flex-direction: row; justify-content: flex-start">

需要成为。

<div style={{ display: "flex"; flexDirection: "row"; justifyContent: "flex-start" }}>

因此-需要在键中替换为驼峰式。这些值需要被包裹起来,"并且"整个样式属性的 需要被替换为{{and }}

到目前为止,我做了以下功能。

function toReactStyle(str) {
  return str
    ?.toLowerCase()
    .replace(";", ",")
    .replace(/-(.)/g, function ($1) {
      return $1.toUpperCase();
    })
    .replace("-", "");
}


const $ = cheerio.load(node.value);
const div = $("div");
const style = div.attr("style");
div.attr("style", `{{${toReactStyle(style)}}}`);

然而,这并没有涵盖完整的预期结果,看起来也不是很有效。还没有围绕值的引号。仅删除了第一个连字符。

{{display: flex, justifyContent: flext-Start; align-Items: center;}}

我还尝试找到一些可以为我执行此操作的现有库,但到目前为止找不到。有没有人知道可以做到这一点的现有库,或者有 Rockstar Regex 技能的人可以解释使用哪个 Regex 以及 Regex 如何工作?

我挣扎的事情是只用引号将值括起来。并且只将钥匙放在驼峰上,并且只-从钥匙中取出。

标签: javascripthtmlcssreactjsregex

解决方案


您可以使用

const $ = cheerio.load(node.value);
const div = $("div");
const style = div.attr("style");
const newstyle = "{{ " + s.replace( /([\w.-]+):\s*([^\s;]*)/g, (x,y,z) => `${y.replace(/-(.)/g, (m,n) => n.toUpperCase())}: "${z}"`) + "}}";
div.attr("style", newstyle);

([\w.-]+):\s*([^\s;]*)则表达式匹配并捕获键(进入第 1 组)和值(进入第 2 组),然后将第 1 组值转换为所需格式并与第 2 组值连接。

请参阅正则表达式演示

JavaScript 演示:

const oldstyle = "display: flex; flex-direction: row; justify-content: flex-start";
console.log(
  "{{ " + oldstyle.replace( /([\w.-]+):\s*([^\s;]*)/g, (x,y,z) => `${y.replace(/-(.)/g, (m,n) => n.toUpperCase())}: "${z}"`) + "}}"
)


推荐阅读