【问题标题】:How to prettify dynamic code snippets in React?如何在 React 中美化动态代码片段?
【发布时间】:2020-04-08 03:59:42
【问题描述】:

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

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

【问题讨论】:

  • 您可以使用prettier 来美化您的代码。这是链接:prettier.io/docs/en/browser.html
  • @YashJoshi 哦 - 我可以在浏览器中使用 Prettier 吗?我不知道。我可以将它导入我的 React 组件,是吗?我在使用其他美化器时遇到的问题是它们只支持 node 或 vanilla JS。
  • 是的,我发送的链接是在浏览器中使用 prettier 的指南。是的,您可以导入并使用它。

标签: reactjs google-code-prettify js-beautify react-ace


【解决方案1】:

感谢这个问题,您可以使用 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>
  );
}

希望这会有所帮助!

【讨论】:

  • 谢谢!我今天要试一试,我会让你知道会发生什么:)
猜你喜欢
  • 2016-09-29
  • 2015-12-14
  • 1970-01-01
  • 2021-03-10
  • 2015-08-22
  • 2016-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多