簡體   English   中英

如何在 React 中美化動態代碼片段?

[英]How to prettify dynamic code snippets in React?

我研究了 google-code-prettify、beautify 等代碼美化工具。不幸的是,我無法在我的 React 應用程序中使用這些美化工具。 我目前正在使用 react-ace 來顯示動態填充的代碼片段,但它們只是顏色突出顯示,沒有格式化。

有什么簡單的例子可以讓我在 React App 中使用它嗎? 它不必使用 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>
  );
}

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM