用React构建免费联系人二维码生成器并部署到GitHub Pages
我将分享如何用React构建自己的二维码生成器,并使用GitHub Pages免费部署。
二维码生成器
在数字时代,分享联系信息应该快速且轻松。我的兄弟在高效地与客户交换联系方式方面遇到了挑战。传统名片虽然有效,但有其局限性,而在线二维码生成器等替代解决方案通常需要付费或注册,这很不方便。这促使我开发了一个免费、易用的联系人二维码生成器。在这篇博客中,我将分享如何用React构建自己的生成器,并使用GitHub Pages免费部署。
设置项目
先决条件
- React和JavaScript的基本知识
- 计算机上安装了Node.js和npm
- 一个GitHub账户
步骤1:创建React应用
首先使用Create React App创建一个新的React应用:
npx create-react-app contact-qr-code-generator
cd contact-qr-code-generator
步骤2:添加TailwindCSS
为了轻松美化我们的UI,我们将使用TailwindCSS:
npm install tailwindcss postcss autoprefixer
npx tailwindcss init -p
在tailwind.config.js中,配置purge选项:
module.exports = {
purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
// ... 其他配置
};
在CSS中引入Tailwind(在src/index.css中):
@tailwind base;
@tailwind components;
@tailwind utilities;
步骤3:构建二维码生成器组件
创建一个新文件src/QRCodeGenerator.js:
import React, { useState } from 'react';
import QRCode from 'qrcode.react';
function QRCodeGenerator() {
const [name, setName] = useState('');
const [phone, setPhone] = useState('');
const [email, setEmail] = useState('');
const generateVCard = () => {
return `BEGIN:VCARD
VERSION:3.0
FN:${name}
TEL:${phone}
EMAIL:${email}
END:VCARD`;
};
return (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<div className="bg-white p-8 rounded-lg shadow-md">
<h1 className="text-2xl font-bold mb-4">联系人二维码生成器</h1>
<input
type="text"
placeholder="姓名"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full p-2 mb-2 border rounded"
/>
<input
type="tel"
placeholder="电话"
value={phone}
onChange={(e) => setPhone(e.target.value)}
className="w-full p-2 mb-2 border rounded"
/>
<input
type="email"
placeholder="邮箱"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full p-2 mb-4 border rounded"
/>
{name && (
<div className="flex justify-center">
<QRCode value={generateVCard()} size={200} />
</div>
)}
</div>
</div>
);
}
export default QRCodeGenerator;
步骤4:部署到GitHub Pages
安装gh-pages包:
npm install gh-pages --save-dev
在package.json中添加以下脚本:
{
"homepage": "https://你的用户名.github.io/contact-qr-code-generator",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
}
然后运行:
npm run deploy
结语
就这样!你现在有了一个免费托管在GitHub Pages上的联系人二维码生成器。这个工具消除了对付费服务的需求,并提供了一种简单的方式来即时生成联系人二维码。
该项目展示了现代Web技术的强大功能以及社区需求如何推动有用工具的创建。希望这能激励你构建解决你周围问题的工具。
Disclaimer: The insights and narratives shared here are purely personal contemplations and imaginings. They do not reflect the strategies, opinions, or beliefs of any entities I am associated with professionally. These musings are crafted from my individual perspective and experience.