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);

 

posted @ 2022-03-29 11:57  洛晨随风  阅读(3169)  评论(0编辑  收藏  举报