react-diff-view的入门使用(文本对比工具)
react-diff-viewer依赖的是react16,对于17版本来说,只能使用react-diff-view做文本对比(目前只发现了这个)
效果:
代码:
import React, { Component } from "react";
import "react-diff-view/style/index.css";
const {
parseDiff,
Diff,
Hunk,
Decoration,
tokenize,
markEdits,
} = require("react-diff-view");
const { diffLines, formatLines } = require("unidiff");
//@ts-ignore
const Appdiff = ({ oldVal, newVal }) => {
//比较新值和旧值的方法
const diffText = formatLines(diffLines(oldVal, newVal), {
context: 3,
});
const files = parseDiff(diffText, { nearbySequences: "zip" });
const renderFile = ({
//@ts-ignore
oldRevision, //@ts-ignore
newRevision, //@ts-ignore
type, //@ts-ignore
hunks,
}) => {
//不一样的地方用高亮表示
const options = {
highlight: false,
enhancers: [markEdits(hunks, { type: "block" })],
};
const token = tokenize(hunks, options);
return (
{/* split就是分左右两个区域做对比 */}
{/* @ts-ignore */}
{(hunks) =>
hunks.map((hunk: { content: {} | null | undefined }) => [
// 作用未知
//
// {hunk.content}
// ,
//这里是核心的渲染区
,
])
}
);
};
return {files.map(renderFile)};
};
function App(props: { oldVal: string; newVal: string }) {
return (
);
}
export default React.memo(App);
测试:
import React, { useState } from "react";
import 文本对比 from "./文本对比";
const Index = () => {
const [oldVal, setOldVal] = useState("");
const [newVal, setNewVal] = useState("");
return (
旧的
<input
type="text"
value={oldVal}
onChange={(v) => {
setOldVal(v.target.value);
}}
/>
新的
<input
type="text"
value={newVal}
onChange={(v) => {
setNewVal(v.target.value);
}}
/>
<文本对比 oldVal={oldVal} newVal={newVal} />
);
};
export default React.memo(Index);