首页 > 解决方案 > 如何在 React 中美化动态代码片段?

问题描述

我研究了 google-code-prettify、beautify 等代码美化工具。不幸的是,我无法在我的 React 应用程序中使用这些美化工具。我目前正在使用 react-ace 来显示动态填充的代码片段,但它们只是颜色突出显示,没有格式化。

有什么简单的例子可以让我在 React App 中使用它吗?它不必使用 Ace 编辑器——这是我的一种技巧,可以让代码显示得很好。

标签: reactjsgoogle-code-prettifyjs-beautifyreact-ace

解决方案


感谢这个问题,您可以使用 prettier 来格式化代码。您可能需要根据您使用的语言或框架配置不同的解析器。

这是一个用于格式化 JS 代码的示例代码框。链接:https ://codesandbox.io/s/currying-architecture-tm785?file=/src/App.js

主文件代码:

import React from "react";
import prettier from "prettier/standalone";
import babylon from "prettier/parser-babel";

import "./styles.css";

export default function App() {
  const [code, setCode] = React.useState(`
        const a = "abc";


                const b = 'a'


           console.log(a);       
  `);

  const formatCode = () => {
    const formattedCode = prettier.format(code, {
      parser: "babel",
      plugins: [babylon]
    });

    setCode(formattedCode);
  };

  return (
    <div className="App">
      <textarea
        style={{ height: "100px", width: "100%", display: "block" }}
        value={code}
      />
      <button onClick={formatCode}>Format Code with Prettier</button>
    </div>
  );
}

希望这可以帮助!


推荐阅读