React JS 中的 SVG 变形

SVG 变形非常有用,你可以用漂亮的动画来变形 SVG 图像,看起来真的很棒。当一个 SVG 更改为另一个 SVG 时,它是一种在两个 SVG 图像之间进行转换的技术。

首先创建一个 React 项目 -

npx create-react-app tutorialpurpose

转到项目目录 -

cd tutorialpurpose

示例

下载并安装react-svg-morph包 -

npm install react-svg-morph --save

这个包将允许我们为我们的 SVG 实现预制的变形动画。

在App.js中添加以下代码行-

import React from "react";
import ReactDOM from "react-dom";
import { MorphReplace } from "react-svg-morph";

class Checked extendsReact.Component{
   render() {
      return (
         <svg width="24" fill="#00ea00" height="24" viewBox="0 0 24 24">
            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41- 1.41z" />
         </svg>
      );
   }
}

class CheckBox extendsReact.Component{
   render() {
      return (
         <svg width="24" height="24" fill="#666666" viewBox="0 0 24 24">
            <path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" />
         </svg>
      );
   }
}

export default class App extendsReact.Component{
   constructor(props) {
      super(props);
     this.state= {
         checked: false,
      };
   }
   toggleChecked() {
      this.setState({ checked: !this.state.checked });
   }
   render() {
      return (
         <div onClick={this.toggleChecked.bind(this)}>
            <MorphReplace width={100} height={100}>{this.state.checked ? ( <Checked key="checked" /> ) : (
               <CheckBox key="checkbox" />)}
            </MorphReplace>
         </div>
      );
   }
}

解释

代码几乎是不言自明的。

  • 我们创建了两个 SVG 类。

  • 然后我们创建了一个类,其中我们有一个函数可以将状态更改为真或假。

  • 然后我们创建了一个MorphReplace组件,在其中添加了我们的两个 SVG,当我们点击它们时它们会发生变化。

输出结果

现在,让我们检查输出 -