reactjs - 如何在 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>
);
}
希望这可以帮助!
推荐阅读
- postgresql - PostgreSQL 中最早和最早的时间
- excel - Excel 宏 - 将数据从一张表传输到另一张表时发送自动电子邮件(复制整行)
- python - 即使在通过 Selenium Python 升级到 v0.23 之后,Geckodriver 仍试图访问旧版本 v0.19
- javascript - 当我只想为一个输入字段显示错误气泡时,如何正确使用 reportValidity()?
- java - 使用 Prometheus 检测 Java 应用程序
- spring-boot - Spring Boot YAML 绑定:绑定属性失败
- sql - 使用 CASE 语句时的 Oracle SQLPLUS AVG 函数
- python - 从 for 循环输出 Python 连接大数据帧
- c - 如何从c中的文件中获取元数据
- python - 使用 Python 和正则表达式从字符串中提取子字符串