1. 程式人生 > 其它 >react-diff-view的入門使用(文字對比工具)

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 ( <div key={oldRevision + "-" + newRevision} className="file-diff"> {
/* split就是分左右兩個區域做對比 */} <Diff viewType="split" diffType={type} hunks={hunks} tokens={token}> {/* @ts-ignore */} {(hunks) => hunks.map((hunk: { content: {} | null | undefined }) => [ // 作用未知 // <Decoration key={"deco-" + hunk.content}> // <div className="hunk-header">{hunk.content}</div> // </Decoration>, //這裡是核心的渲染區 <Hunk key={hunk.content} hunk={hunk} />, ]) } </Diff> </div> ); }; return <div>{files.map(renderFile)}</div>; }; function App(props: { oldVal: string; newVal: string }) { return ( <div className="App"> <Appdiff oldVal={props.oldVal} newVal={props.newVal} /> </div> ); } export default React.memo(App);

測試:

import React, { useState } from "react";
import 文字對比 from "./文字對比";

const Index = () => {
  const [oldVal, setOldVal] = useState("");
  const [newVal, setNewVal] = useState("");
  return (
    <div>
      舊的
      <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} />
    </div>
  );
};

export default React.memo(Index);