利用 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 extends React.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 extends React.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 extends React.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 类。
然后我们创建了一个 main 类,其中有一个函数可以将状态更改为 true 或 false。
然后我们在 MorphReplace 组件内部添加了两个 SVG,当我们单击它们时,它们将发生变化。
输出
现在,让我们检查一下输出 −
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP