乐闻世界logo
搜索文章和话题

面试题手册

什么是 Hardhat Ignition 及其使用方法?

Hardhat Ignition 是 Hardhat 的声明式部署系统,提供了更强大和可维护的部署方式:核心概念:模块化部署使用模块定义部署逻辑支持模块间的依赖关系声明式配置而非命令式脚本部署状态管理自动跟踪部署状态支持增量部署避免重复部署基本使用:创建部署模块:const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules");module.exports = buildModule("TokenModule", (m) => { const token = m.contract("MyToken", ["MyToken", "MTK", 18]); return { token };});高级功能:参数化部署module.exports = buildModule("TokenModule", (m) => { const name = m.getParameter("name", "MyToken"); const symbol = m.getParameter("symbol", "MTK"); const token = m.contract("MyToken", [name, symbol, 18]); return { token };});依赖管理module.exports = buildModule("DAppModule", (m) => { const token = m.contract("MyToken"); const sale = m.contract("TokenSale", [token]); // 调用 token 合约的函数 m.call(token, "transferOwnership", [sale]); return { token, sale };});现有合约使用module.exports = buildModule("Module", (m) => { const existingContract = m.contractAt( "ExistingContract", "0x1234..." ); return { existingContract };});部署命令:# 部署到本地网络npx hardhat ignition deploy ./ignition/modules/Module.js# 部署到测试网npx hardhat ignition deploy ./ignition/modules/Module.js --network sepolia# 使用参数部署npx hardhat ignition deploy ./ignition/modules/Module.js --parameters name:CustomToken,symbol:CTK# 验证部署npx hardhat ignition deploy ./ignition/modules/Module.js --verify部署计划:Ignition 会生成部署计划,显示将要执行的操作:npx hardhat ignition plan ./ignition/modules/Module.js优势:声明式配置更易理解自动处理部署依赖支持部署验证更好的错误处理适合复杂的多合约部署便于团队协作
阅读 0·2月21日 15:59

JavaScript 如何操作和操作 SVG

JavaScript 与 SVG 的结合可以实现强大的动态交互功能。以下是 JavaScript 操作 SVG 的主要方法:1. 选择 SVG 元素使用标准 DOM 方法选择 SVG 元素。// 通过 ID 选择const circle = document.getElementById('myCircle');// 通过类名选择const circles = document.querySelectorAll('.circle');// 通过标签名选择const allRects = document.querySelectorAll('rect');// 通过属性选择const filledElements = document.querySelectorAll('[fill="red"]');2. 创建 SVG 元素使用 createElementNS 创建 SVG 元素(注意命名空间)。const svgNS = 'http://www.w3.org/2000/svg';// 创建 SVG 元素const circle = document.createElementNS(svgNS, 'circle');circle.setAttribute('cx', '100');circle.setAttribute('cy', '100');circle.setAttribute('r', '50');circle.setAttribute('fill', 'blue');// 添加到 SVGconst svg = document.querySelector('svg');svg.appendChild(circle);3. 修改 SVG 属性使用 setAttribute 和 getAttribute 方法。const circle = document.querySelector('circle');// 修改属性circle.setAttribute('fill', 'red');circle.setAttribute('r', '60');circle.setAttribute('stroke', 'black');circle.setAttribute('stroke-width', '3');// 获取属性const fill = circle.getAttribute('fill');const radius = circle.getAttribute('r');4. 修改 SVG 样式使用 style 属性或 classList。const circle = document.querySelector('circle');// 直接设置样式circle.style.fill = 'green';circle.style.opacity = '0.5';circle.style.transform = 'scale(1.2)';// 使用 classListcircle.classList.add('highlight');circle.classList.remove('normal');circle.classList.toggle('active');5. 事件监听为 SVG 元素添加事件监听器。const circle = document.querySelector('circle');// 鼠标事件circle.addEventListener('click', function() { console.log('Circle clicked!'); this.setAttribute('fill', 'red');});circle.addEventListener('mouseover', function() { this.style.cursor = 'pointer';});circle.addEventListener('mouseout', function() { this.style.cursor = 'default';});// 键盘事件(需要 tabindex)circle.setAttribute('tabindex', '0');circle.addEventListener('keydown', function(event) { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); console.log('Circle activated!'); }});6. 动画实现使用 JavaScript 实现 SVG 动画。const circle = document.querySelector('circle');// 使用 requestAnimationFramelet progress = 0;function animate() { progress += 0.01; const x = 100 + Math.sin(progress * 2 * Math.PI) * 50; circle.setAttribute('cx', x); if (progress < 1) { requestAnimationFrame(animate); }}animate();// 使用 CSS 过渡circle.style.transition = 'all 0.5s ease';circle.setAttribute('fill', 'red');circle.setAttribute('r', '60');7. 获取鼠标位置获取鼠标在 SVG 中的相对位置。const svg = document.querySelector('svg');svg.addEventListener('click', function(event) { const point = svg.createSVGPoint(); point.x = event.clientX; point.y = event.clientY; const svgPoint = point.matrixTransform(svg.getScreenCTM().inverse()); console.log(`SVG coordinates: x=${svgPoint.x}, y=${svgPoint.y}`);});8. 拖拽功能实现 SVG 元素的拖拽。let selectedElement = null;let offset = { x: 0, y: 0 };function getMousePosition(evt) { const CTM = svg.getScreenCTM(); return { x: (evt.clientX - CTM.e) / CTM.a, y: (evt.clientY - CTM.f) / CTM.d };}function startDrag(evt) { selectedElement = evt.target; offset = getMousePosition(evt); offset.x -= parseFloat(selectedElement.getAttribute('cx')); offset.y -= parseFloat(selectedElement.getAttribute('cy'));}function drag(evt) { if (selectedElement) { evt.preventDefault(); const coord = getMousePosition(evt); selectedElement.setAttribute('cx', coord.x - offset.x); selectedElement.setAttribute('cy', coord.y - offset.y); }}function endDrag(evt) { selectedElement = null;}const svg = document.querySelector('svg');svg.addEventListener('mousedown', startDrag);svg.addEventListener('mousemove', drag);svg.addEventListener('mouseup', endDrag);svg.addEventListener('mouseleave', endDrag);9. 动态创建复杂图形使用 JavaScript 动态创建复杂的 SVG 图形。function createStar(cx, cy, spikes, outerRadius, innerRadius) { const svgNS = 'http://www.w3.org/2000/svg'; const polygon = document.createElementNS(svgNS, 'polygon'); let points = []; for (let i = 0; i < spikes * 2; i++) { const radius = i % 2 === 0 ? outerRadius : innerRadius; const angle = (Math.PI / spikes) * i; const x = cx + Math.cos(angle) * radius; const y = cy + Math.sin(angle) * radius; points.push(`${x},${y}`); } polygon.setAttribute('points', points.join(' ')); polygon.setAttribute('fill', 'gold'); polygon.setAttribute('stroke', 'orange'); polygon.setAttribute('stroke-width', '2'); return polygon;}const svg = document.querySelector('svg');const star = createStar(100, 100, 5, 50, 25);svg.appendChild(star);10. 数据可视化使用 SVG 和 JavaScript 创建数据可视化。const data = [10, 25, 40, 30, 50];const svg = document.querySelector('svg');const barWidth = 40;const gap = 20;data.forEach((value, index) => { const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); const x = 20 + index * (barWidth + gap); const y = 200 - value * 3; rect.setAttribute('x', x); rect.setAttribute('y', y); rect.setAttribute('width', barWidth); rect.setAttribute('height', value * 3); rect.setAttribute('fill', `hsl(${index * 60}, 70%, 50%)`); svg.appendChild(rect);});最佳实践:使用 createElementNS 创建 SVG 元素合理使用事件委托优化动画性能,使用 requestAnimationFrame注意命名空间考虑使用 SVG 库(如 D3.js)处理复杂场景测试跨浏览器兼容性
阅读 0·2月21日 15:58

Expo应用如何实现国际化(i18n)?有哪些推荐的库?

Expo应用的国际化(i18n)是面向全球用户的重要功能。Expo支持多种国际化解决方案,使开发者能够轻松实现多语言支持。国际化库选择:i18next最流行的国际化库,功能强大且易于使用。安装:npm install i18next react-i18next expo-localization配置i18next:// i18n.tsimport i18n from 'i18next';import { initReactI18next } from 'react-i18next';import { getLocales } from 'expo-localization';const resources = { en: { translation: { welcome: 'Welcome', login: 'Login', logout: 'Logout', 'hello.name': 'Hello, {{name}}!', }, }, zh: { translation: { welcome: '欢迎', login: '登录', logout: '退出', 'hello.name': '你好,{{name}}!', }, },};i18n .use(initReactI18next) .init({ resources, lng: getLocales()[0]?.languageCode || 'en', fallbackLng: 'en', interpolation: { escapeValue: false, }, });export default i18n;使用i18next:import { useTranslation } from 'react-i18next';function WelcomeScreen() { const { t, i18n } = useTranslation(); const changeLanguage = (lang: string) => { i18n.changeLanguage(lang); }; return ( <View> <Text>{t('welcome')}</Text> <Text>{t('hello.name', { name: 'John' })}</Text> <Button title="English" onPress={() => changeLanguage('en')} /> <Button title="中文" onPress={() => changeLanguage('zh')} /> </View> );}expo-localizationExpo官方的本地化库,用于获取设备语言设置。使用expo-localization:import * as Localization from 'expo-localization';function getDeviceLanguage() { const locale = Localization.locale; const languageCode = Localization.locale.split('-')[0]; console.log('Locale:', locale); console.log('Language:', languageCode); return languageCode;}获取本地化信息:function getLocalizationInfo() { const locale = Localization.locale; const timezone = Localization.timezone; const isoCurrencyCodes = Localization.isoCurrencyCodes; return { locale, timezone, currency: isoCurrencyCodes[0], };}React Native Localization轻量级的国际化解决方案。安装:npm install react-native-localize配置:import * as RNLocalize from 'react-native-localize';const translations = { en: require('./en.json'), zh: require('./zh.json'),};const fallback = { languageTag: 'en', isRTL: false };const { languageTag } = RNLocalize.findBestAvailableLanguage(Object.keys(translations)) || fallback;i18n.init({ resources: { [languageTag]: translations[languageTag], }, lng: languageTag, fallbackLng: 'en',});多语言资源管理:JSON文件结构// locales/en.json{ "common": { "ok": "OK", "cancel": "Cancel", "save": "Save" }, "auth": { "login": "Login", "logout": "Logout", "register": "Register", "forgotPassword": "Forgot Password?" }, "home": { "title": "Home", "welcome": "Welcome back!", "recentActivity": "Recent Activity" }}// locales/zh.json{ "common": { "ok": "确定", "cancel": "取消", "save": "保存" }, "auth": { "login": "登录", "logout": "退出", "register": "注册", "forgotPassword": "忘记密码?" }, "home": { "title": "首页", "welcome": "欢迎回来!", "recentActivity": "最近活动" }}命名空间组织// 使用命名空间i18n.init({ resources: { en: { common: require('./locales/en/common.json'), auth: require('./locales/en/auth.json'), home: require('./locales/en/home.json'), }, zh: { common: require('./locales/zh/common.json'), auth: require('./locales/zh/auth.json'), home: require('./locales/zh/home.json'), }, },});// 使用命名空间const { t } = useTranslation('common');<Text>{t('ok')}</Text>// 跨命名空间<Text>{t('auth:login')}</Text>日期和时间本地化:import { format } from 'date-fns';import { zhCN, enUS } from 'date-fns/locale';function formatDate(date: Date, locale: string) { const localeMap = { en: enUS, zh: zhCN, }; return format(date, 'PPP', { locale: localeMap[locale] || enUS, });}function formatDateTime(date: Date, locale: string) { return format(date, 'PPPppp', { locale: locale === 'zh' ? zhCN : enUS, });}数字和货币本地化:function formatCurrency(amount: number, locale: string) { return new Intl.NumberFormat(locale, { style: 'currency', currency: locale === 'zh' ? 'CNY' : 'USD', }).format(amount);}function formatNumber(number: number, locale: string) { return new Intl.NumberFormat(locale).format(number);}function formatPercent(value: number, locale: string) { return new Intl.NumberFormat(locale, { style: 'percent', minimumFractionDigits: 2, }).format(value);}RTL(从右到左)支持:import { I18nManager } from 'react-native';function setupRTL(locale: string) { const isRTL = locale === 'ar' || locale === 'he'; if (I18nManager.isRTL !== isRTL) { I18nManager.allowRTL(isRTL); I18nManager.forceRTL(isRTL); // 需要重启应用 Updates.reloadAsync(); }}动态语言切换:function LanguageSwitcher() { const { i18n } = useTranslation(); const [currentLang, setCurrentLang] = useState(i18n.language); const changeLanguage = async (lang: string) => { await i18n.changeLanguage(lang); setCurrentLang(lang); // 保存用户偏好 await AsyncStorage.setItem('userLanguage', lang); // 如果需要RTL支持 setupRTL(lang); }; const languages = [ { code: 'en', name: 'English' }, { code: 'zh', name: '中文' }, { code: 'es', name: 'Español' }, ]; return ( <View> {languages.map((lang) => ( <Button key={lang.code} title={lang.name} onPress={() => changeLanguage(lang.code)} disabled={currentLang === lang.code} /> ))} </View> );}最佳实践:资源文件组织按功能模块组织翻译文件使用命名空间避免冲突保持翻译文件结构一致翻译质量使用专业的翻译工具考虑文化差异和习惯定期审查和更新翻译性能优化按需加载语言包缓存翻译结果避免频繁的语言切换用户体验自动检测设备语言提供语言切换选项保存用户语言偏好测试覆盖测试所有语言的显示检查文本溢出问题验证RTL布局常见问题:翻译缺失设置fallback语言使用翻译管理工具定期检查翻译完整性文本溢出使用flex布局提供文本截断选项为不同语言调整布局动态加载使用代码分割懒加载语言包预加载常用语言通过完善的国际化实现,Expo应用可以更好地服务全球用户,提升用户体验和市场竞争力。
阅读 0·2月21日 15:58

Hardhat 中的调试技巧有哪些?

Hardhat 提供了强大的调试功能,以下是主要的调试技巧:1. Console.log 调试在 Solidity 合约中使用 console.log:import "hardhat/console.sol";contract MyContract { function setValue(uint256 _value) public { console.log("Setting value to:", _value); value = _value; console.log("Value set successfully"); }}2. 交易回溯使用 hardhat --verbose 查看详细交易信息:npx hardhat test --verbose在测试中捕获错误堆栈:try { await contract.someFunction();} catch (error) { console.log(error);}3. Hardhat Network 控制台启动交互式控制台:npx hardhat console在控制台中执行命令:const Contract = await ethers.getContractFactory("MyContract");const contract = await Contract.deploy();await contract.setValue(42);console.log(await contract.value());4. 调试测试使用 --debug 标志运行测试:npx hardhat test --debug5. 查看事件监听合约事件:contract.on("EventName", (arg1, arg2, event) => { console.log("Event emitted:", arg1, arg2);});6. 状态快照使用快照功能快速重置状态:const snapshot = await ethers.provider.send("evm_snapshot", []);// 执行操作await ethers.provider.send("evm_revert", [snapshot]);7. Gas 分析使用 gas-reporter 插件分析 Gas 使用:npx hardhat test --gas最佳实践:在开发阶段大量使用 console.log生产环境移除 console.sol 导入使用有意义的日志信息结合事件和日志进行调试利用快照功能提高测试效率
阅读 0·2月21日 15:58

Jest 中有哪些测试匹配器(Matchers)?如何使用自定义匹配器?

Jest 提供了多种测试匹配器(Matchers)来验证不同的条件:相等性匹配器:toBe(value):严格相等(===)toEqual(value):深度相等toStrictEqual(value):严格深度相等(包括 undefined 属性)toMatchObject(object):部分匹配对象真值匹配器:toBeNull():只匹配 nulltoBeUndefined():只匹配 undefinedtoBeDefined():非 undefinedtoBeTruthy():真值toBeFalsy():假值数字匹配器:toBeGreaterThan(number):大于toBeGreaterThanOrEqual(number):大于等于toBeLessThan(number):小于toBeLessThanOrEqual(number):小于等于toBeCloseTo(number, precision):浮点数近似相等字符串匹配器:toMatch(regexp | string):匹配正则或字符串toContain(item):包含元素或子字符串数组匹配器:toContain(item):包含元素toContainEqual(item):包含相等元素toHaveLength(number):数组长度toBeArray():是数组对象匹配器:toHaveProperty(keyPath, value):有特定属性toMatchObject(object):部分匹配对象函数匹配器:toHaveBeenCalled():被调用toHaveBeenCalledWith(...args):用特定参数调用toHaveBeenCalledTimes(n):调用次数toHaveReturned():返回值toHaveReturnedWith(value):返回特定值异常匹配器:toThrow(error?):抛出错误toThrowErrorMatchingSnapshot():错误快照自定义匹配器:expect.extend({ toBeWithinRange(received, floor, ceiling) { const pass = received >= floor && received <= ceiling; return { pass, message: () => pass ? `expected ${received} not to be within range ${floor}-${ceiling}` : `expected ${received} to be within range ${floor}-${ceiling}` }; }});test('number within range', () => { expect(100).toBeWithinRange(90, 110);});否定匹配器:所有匹配器都可以使用 .not 进行否定:expect(value).not.toBe(42);expect(array).not.toContain('item');
阅读 0·2月21日 15:57

如何在 Jest 中测试 React Hooks?如何使用 renderHook 和 act?

Jest 提供了多种测试 React Hooks 的方法,主要使用 @testing-library/react-hooks:1. 测试 useState:import { renderHook, act } from '@testing-library/react-hooks';test('useState hook', () => { const { result } = renderHook(() => useCounter(0)); expect(result.current.count).toBe(0); act(() => { result.current.increment(); }); expect(result.current.count).toBe(1);});2. 测试 useEffect:test('useEffect hook', () => { const { result } = renderHook(() => useFetch('/api/data')); expect(result.current.loading).toBe(true); await act(async () => { await waitFor(() => !result.current.loading); }); expect(result.current.data).toBeDefined();});3. 测试 useContext:test('useContext hook', () => { const wrapper = ({ children }) => ( <ThemeContext.Provider value="dark"> {children} </ThemeContext.Provider> ); const { result } = renderHook(() => useTheme(), { wrapper }); expect(result.current.theme).toBe('dark');});4. 测试自定义 Hook:function useCustomHook(initialValue) { const [value, setValue] = useState(initialValue); const double = useMemo(() => value * 2, [value]); return { value, setValue, double };}test('custom hook', () => { const { result } = renderHook(() => useCustomHook(5)); expect(result.current.value).toBe(5); expect(result.current.double).toBe(10); act(() => { result.current.setValue(10); }); expect(result.current.double).toBe(20);});5. 测试异步 Hook:test('async hook', async () => { const { result, waitForNextUpdate } = renderHook(() => useAsyncData()); expect(result.current.loading).toBe(true); await waitForNextUpdate(); expect(result.current.loading).toBe(false); expect(result.current.data).toBeDefined();});6. 测试错误处理:test('hook error handling', async () => { const { result, waitForNextUpdate } = renderHook(() => useFetch('/invalid')); await waitForNextUpdate(); expect(result.current.error).toBeInstanceOf(Error);});最佳实践:使用 renderHook 测试 Hook使用 act 包装状态更新测试 Hook 的初始状态和更新后的状态测试异步 Hook 时使用 waitFor 或 waitForNextUpdate测试错误边界情况保持测试简单,专注于 Hook 的行为
阅读 0·2月21日 15:57