diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..610bcd3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,390 @@ +### Gradle ### +.gradle +build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Cache of project +.gradletasknamecache + +# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 +# gradle/wrapper/gradle-wrapper.properties + +### Gradle Patch ### +**/build/ + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +.idea/sonarlint + + +### Intellij+iml ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+iml Patch ### +# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 + +*.iml +modules.xml +.idea/misc.xml +*.ipr + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar +.flattened-pom.xml + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +.idea/sonarlint + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage +*.lcov + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) +web_modules/ + +# TypeScript cache +*.tsbuildinfo + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional stylelint cache +.stylelintcache + +# Microbundle cache +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) +.cache +.parcel-cache + +# Next.js build output +.next +out + +# Nuxt.js build / generate output +.nuxt +dist + +# Gatsby files +.cache/ +# Comment in the public line in if your project uses Gatsby and not Next.js +# https://nextjs.org/blog/next-9-1#public-directory-support +# public + +# vuepress build output +.vuepress/dist + +# vitepress cache output +.vitepress/cache + +# vuepress v2.x temp and cache directory +.temp + +# Docusaurus cache and generated files +.docusaurus + +# Serverless directories +.serverless/ + +# FuseBox cache +.fusebox/ + +# DynamoDB Local files +.dynamodb/ + +# TernJS port file +.tern-port + +# Stores VSCode versions used for testing VSCode extensions +.vscode-test + +# yarn v2 +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.* + +### Node Patch ### +# Serverless Webpack directories +.webpack/ + +# Optional stylelint cache + +# SvelteKit build / generate output +.svelte-kit + +### VitePress ### +# scripts/sync-zh.mjs 生成的站点源文件(由 src/ 和 i18n/zh/ 组装) +/site/ +# scripts/generate.mjs 生成的配置 +/.vitepress/generated/ +/.vitepress/dist/ +/.vitepress/.temp/ + + +### Cloudflare Wrangler ### +.wrangler/ diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..f3b42f4 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,12 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Markdown personal settings +/markdown.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/checkstyle-idea.xml b/.idea/checkstyle-idea.xml new file mode 100644 index 0000000..c903334 --- /dev/null +++ b/.idea/checkstyle-idea.xml @@ -0,0 +1,16 @@ + + + + 14.5.0 + JavaOnly + true + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.vitepress/config.mts b/.vitepress/config.mts new file mode 100644 index 0000000..dcbabf6 --- /dev/null +++ b/.vitepress/config.mts @@ -0,0 +1,285 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { defineConfig, type DefaultTheme, type LocaleConfig } from 'vitepress'; + +type NavSection = { text: string; zh?: string; base: string }; + +// Sidebar items from scripts/nav.json: `zh` is the Chinese title, `version` a react.dev release tag. +type GeneratedSidebarItem = DefaultTheme.SidebarItem & { + zh?: string; + version?: string; + items?: GeneratedSidebarItem[]; +}; + +type GeneratedLocale = { + label: string; + base: string; + sections: NavSection[]; + sidebar: Record; +}; + +const siteFile = path.join(path.dirname(fileURLToPath(import.meta.url)), 'generated', 'site.json'); +if (!fs.existsSync(siteFile)) + throw new Error('Run "node scripts/generate.mjs" first. The file .vitepress/generated/site.json is missing.'); +const site: { locales: Record } = JSON.parse(fs.readFileSync(siteFile, 'utf8')); +const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const englishSrcDir = path.join(rootDir, 'src'); + +const EN_PREFIX = '/en'; +const FORUM_URL = 'https://www.isharkfly.com/tag/react'; +const SOURCE_URL = 'https://src.sharkdat.com/iSharkFly-Docs/React'; + +// iSharkFly links shown as a dropdown at the end of the nav bar. +function isharkflyNav(zh: boolean): DefaultTheme.NavItem { + return { + text: 'iSharkFly', + items: [ + { text: zh ? 'iSharkFly 论坛' : 'iSharkFly Forum', link: FORUM_URL }, + { text: zh ? '文档导航' : 'Docs Portal', link: 'https://docs.isharkfly.com/' }, + { text: zh ? '本站源码' : 'Source Code', link: SOURCE_URL }, + ], + }; +} + +// Nav bar entries: one per sidebar section, linking to its landing page. +const SECTION_LANDING: Record = { + '/learn/': 'learn', + '/reference/': 'reference/react', + '/community/': 'community', + '/blog/': 'blog', +}; +const ZH_SECTION_TEXT: Record = { + '/learn/': '学习', + '/reference/': 'API 参考', + '/community/': '社区', + '/blog/': '博客', +}; +const EN_SECTION_TEXT: Record = { + '/learn/': 'Learn', + '/reference/': 'Reference', + '/community/': 'Community', + '/blog/': 'Blog', +}; + +// react.dev marks some APIs with a release channel; shown after the title. +const VERSION_BADGE: Record = { + canary: 'Canary', + experimental: 'Experimental', + rc: 'RC', + major: 'React 19', +}; + +function enLink(link: string) { + return link.startsWith('/') ? EN_PREFIX + link : link; +} + +function mapSidebar( + sidebar: Record, + mapLink: (link: string) => string, + zh: boolean, +): DefaultTheme.SidebarMulti { + const mapItems = (items: GeneratedSidebarItem[]): DefaultTheme.SidebarItem[] => items.map(({ zh: zhText, version, items: children, ...item }) => { + const text = (zh && zhText) || item.text || ''; + const badge = version && VERSION_BADGE[version]; + return { + ...item, + text: badge ? `${text} ${badge}` : text, + ...(children ? { items: mapItems(children) } : {}), + ...(item.link ? { link: mapLink(item.link) } : {}), + }; + }); + return Object.fromEntries(Object.entries(sidebar).map(([key, value]) => [mapLink(key), mapItems(value)])); +} + +const zhThemeText: DefaultTheme.Config = { + outline: { level: [2, 3], label: '本页目录' }, + docFooter: { prev: '上一页', next: '下一页' }, + darkModeSwitchLabel: '外观', + lightModeSwitchTitle: '切换到浅色模式', + darkModeSwitchTitle: '切换到深色模式', + sidebarMenuLabel: '菜单', + returnToTopLabel: '回到顶部', + langMenuLabel: '切换语言', + skipToContentLabel: '跳到正文', + notFound: { + title: '页面未找到', + quote: '你要找的页面不存在,或者已经被移动。', + linkLabel: '返回首页', + linkText: '返回首页', + }, + footer: { + message: '文档内容基于 CC BY 4.0 许可证发布,示例代码基于 MIT 许可证发布。', + copyright: 'Copyright © Meta Platforms, Inc.', + }, +}; + +const zhSearchText = { + button: { buttonText: '搜索', buttonAriaLabel: '搜索' }, + modal: { + displayDetails: '显示详细列表', + resetButtonTitle: '清除查询', + backButtonTitle: '关闭搜索', + noResultsText: '没有找到结果', + footer: { + selectText: '选择', + selectKeyAriaLabel: '回车', + navigateText: '切换', + navigateUpKeyAriaLabel: '向上', + navigateDownKeyAriaLabel: '向下', + closeText: '关闭', + closeKeyAriaLabel: 'Esc', + }, + }, +}; + +function sectionNav(locale: GeneratedLocale, base: string, text: Record): DefaultTheme.NavItem[] { + return locale.sections.map(section => ({ + text: text[section.base] ?? section.text, + link: `${base}${SECTION_LANDING[section.base] ?? section.base.slice(1)}`, + activeMatch: `^${base}${section.base.slice(1)}`, + })); +} + +const zhLocales: LocaleConfig = {}; +const enLocales: LocaleConfig = {}; + +for (const [key, locale] of Object.entries(site.locales)) { + zhLocales[key] = { + label: `简体中文`, + lang: 'zh-CN', + link: locale.base, + title: 'React', + description: `React 中文文档:用于构建 Web 和原生交互界面的库`, + themeConfig: { + ...zhThemeText, + nav: [...sectionNav(locale, locale.base, ZH_SECTION_TEXT), isharkflyNav(true)], + sidebar: mapSidebar(locale.sidebar, link => link, true), + }, + }; + + const enBase = enLink(locale.base); + enLocales[key === 'root' ? 'en' : `en/${key}`] = { + label: `English`, + lang: 'en-US', + link: enBase, + title: 'React', + description: `React documentation: the library for web and native user interfaces`, + themeConfig: { + nav: [...sectionNav(locale, enBase, EN_SECTION_TEXT), isharkflyNav(false)], + sidebar: mapSidebar(locale.sidebar, enLink, false), + }, + }; +} + +const locales: LocaleConfig = { ...zhLocales }; +for (const key of Object.keys(enLocales).sort((a, b) => b.length - a.length)) + locales[key] = enLocales[key]; + +function listPages(dir: string, rel = ''): string[] { + if (!fs.existsSync(dir)) + return []; + return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => { + const entryRel = rel + entry.name; + if (entry.isDirectory()) { + if (!rel && (['zh', 'en', 'public'].includes(entry.name) || site.locales[entry.name])) + return []; + return listPages(path.join(dir, entry.name), `${entryRel}/`); + } + return entry.name.endsWith('.md') ? [entryRel] : []; + }); +} + +const pagesByLanguage = Object.fromEntries(Object.keys(site.locales).map(key => [ + key, + listPages(key === 'root' ? englishSrcDir : path.join(englishSrcDir, key)), +])); + +export default defineConfig({ + srcDir: 'site', + srcExclude: ['public/**'], + lang: 'zh-CN', + title: 'React', + description: 'React 中文文档', + cleanUrls: true, + lastUpdated: false, + ignoreDeadLinks: true, + locales, + head: [ + ['link', { rel: 'icon', href: '/favicon.ico' }], + ['link', { rel: 'icon', type: 'image/png', sizes: '32x32', href: '/favicon-32x32.png' }], + ['link', { rel: 'apple-touch-icon', href: '/apple-touch-icon.png' }], + ['meta', { name: 'google-site-verification', content: '6t0LoIeFksrjF4c9sqUEsVXiQNxLp2hgoqo0KryT-sE' }], + // Google Tag Manager + ['script', {}, `(function (w, d, s, l, i) { + w[l] = w[l] || []; + w[l].push({ + 'gtm.start': + new Date().getTime(), event: 'gtm.js' + }); + var f = d.getElementsByTagName(s)[0], + j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; + j.async = true; + j.src = + 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; + f.parentNode.insertBefore(j, f); + })(window, document, 'script', 'dataLayer', 'GTM-W3NL9V');`], + // End Google Tag Manager + // Matomo Tag Manager + ['script', {}, `var _mtm = window._mtm = window._mtm || []; + _mtm.push({'mtm.startTime': (new Date().getTime()), 'event': 'mtm.Start'}); + (function() { + var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; + g.async=true; g.src='https://analytics.sharkdat.com/js/container_yMtZdGlf.js'; s.parentNode.insertBefore(g,s); + })();`], + // End Matomo Tag Manager + ], + markdown: { + theme: { light: 'github-light', dark: 'github-dark' }, + config: md => { + const defaultCodeInline = md.renderer.rules.code_inline!; + md.renderer.rules.code_inline = (tokens, idx, options, env, self) => + defaultCodeInline(tokens, idx, options, env, self).replace(/^ + defaultText(tokens, idx, options, env, self).replace(/\{\{/g, '{{').replace(/\}\}/g, '}}'); + }, + }, + themeConfig: { + logo: '/logo.svg', + search: { + provider: 'local', + options: { + locales: Object.fromEntries(Object.keys(zhLocales).map(key => [key, { translations: zhSearchText }])), + }, + }, + outline: { level: [2, 3] }, + socialLinks: [ + { icon: 'github', link: 'https://github.com/facebook/react' }, + ], + editLink: undefined, + footer: { + message: 'Documentation licensed under CC BY 4.0. Code examples licensed under MIT.', + copyright: 'Copyright © Meta Platforms, Inc.', + }, + languageSwitcher: { + enPrefix: EN_PREFIX, + pages: pagesByLanguage, + }, + } as DefaultTheme.Config, + vite: { + build: { chunkSizeWarningLimit: 4096 }, + resolve: { + alias: [ + { + find: /^.*\/VPNavBarTranslations\.vue$/, + replacement: fileURLToPath(new URL('./theme/components/NavBarLanguageSwitcher.vue', import.meta.url)), + }, + { + find: /^.*\/VPNavScreenTranslations\.vue$/, + replacement: fileURLToPath(new URL('./theme/components/NavScreenLanguageSwitcher.vue', import.meta.url)), + }, + ], + }, + }, +}); diff --git a/.vitepress/theme/components/NavBarLanguageSwitcher.vue b/.vitepress/theme/components/NavBarLanguageSwitcher.vue new file mode 100644 index 0000000..a5855cf --- /dev/null +++ b/.vitepress/theme/components/NavBarLanguageSwitcher.vue @@ -0,0 +1,71 @@ + + + + + diff --git a/.vitepress/theme/components/NavScreenLanguageSwitcher.vue b/.vitepress/theme/components/NavScreenLanguageSwitcher.vue new file mode 100644 index 0000000..a1f7575 --- /dev/null +++ b/.vitepress/theme/components/NavScreenLanguageSwitcher.vue @@ -0,0 +1,85 @@ + + + + + diff --git a/.vitepress/theme/components/UntranslatedNotice.vue b/.vitepress/theme/components/UntranslatedNotice.vue new file mode 100644 index 0000000..d0764cc --- /dev/null +++ b/.vitepress/theme/components/UntranslatedNotice.vue @@ -0,0 +1,35 @@ + + + + + diff --git a/.vitepress/theme/custom.css b/.vitepress/theme/custom.css new file mode 100644 index 0000000..b0c8ffd --- /dev/null +++ b/.vitepress/theme/custom.css @@ -0,0 +1,36 @@ +/* react.dev 品牌色 */ +:root { + --vp-c-brand-1: #087ea4; + --vp-c-brand-2: #0a6d8f; + --vp-c-brand-3: #0b5d79; + --vp-c-brand-soft: rgba(8, 126, 164, 0.14); + + --vp-home-hero-name-color: #087ea4; + --vp-home-hero-image-background-image: radial-gradient(circle, rgba(88, 196, 220, 0.35) 0%, rgba(88, 196, 220, 0) 70%); + --vp-home-hero-image-filter: blur(24px); +} + +.dark { + --vp-c-brand-1: #58c4dc; + --vp-c-brand-2: #3fb3cf; + --vp-c-brand-3: #2a9fbd; + --vp-c-brand-soft: rgba(88, 196, 220, 0.16); + + --vp-home-hero-name-color: #58c4dc; +} + +.VPHero .image-src { + max-width: 240px; + max-height: 240px; +} + +/* 侧边栏中的发布渠道标记(Canary、Experimental 等) */ +.sidebar-badge { + margin-left: 4px; + border-radius: 4px; + padding: 0 4px; + font-size: 11px; + font-weight: 600; + color: var(--vp-c-text-2); + background-color: var(--vp-c-default-soft); +} diff --git a/.vitepress/theme/index.ts b/.vitepress/theme/index.ts new file mode 100644 index 0000000..af1b73f --- /dev/null +++ b/.vitepress/theme/index.ts @@ -0,0 +1,19 @@ +import { h } from 'vue'; +import DefaultTheme from 'vitepress/theme'; +import type { Theme } from 'vitepress'; +import UntranslatedNotice from './components/UntranslatedNotice.vue'; +import { reactComponents } from './react/components'; +import './custom.css'; +import './react/react.css'; + +export default { + extends: DefaultTheme, + Layout: () => h(DefaultTheme.Layout, null, { + 'doc-before': () => h(UntranslatedNotice), + }), + enhanceApp({ app }) { + // react.dev MDX components used in the pages (, , , , ...). + for (const [name, component] of Object.entries(reactComponents)) + app.component(name, component); + }, +} satisfies Theme; diff --git a/.vitepress/theme/languageSwitcher.ts b/.vitepress/theme/languageSwitcher.ts new file mode 100644 index 0000000..06e7a80 --- /dev/null +++ b/.vitepress/theme/languageSwitcher.ts @@ -0,0 +1,58 @@ +import { computed } from 'vue'; +import { useData } from 'vitepress'; + +type SwitcherConfig = { + enPrefix: string; + pages: Record; +}; + +export type SwitcherLink = { text: string; link: string; lang?: string; active: boolean }; + +const READING_LANGUAGES = [ + { key: 'zh', text: '简体中文', lang: 'zh-CN' }, + { key: 'en', text: 'English', lang: 'en-US' }, +] as const; + +function pageUrl(base: string, page: string) { + return base + page.replace(/(^|\/)index\.md$/, '$1').replace(/\.md$/, ''); +} + +export function useLanguageSwitcher() { + const { page, theme, hash } = useData(); + const config = computed(() => theme.value.languageSwitcher as SwitcherConfig); + + const current = computed(() => { + let rest = page.value.relativePath; + const enDir = config.value.enPrefix.replace(/^\//, '') + '/'; + const reading = rest.startsWith(enDir) ? 'en' : 'zh'; + if (reading === 'en') + rest = rest.slice(enDir.length); + return { reading, page: rest }; + }); + + function linkFor(reading: string, keepHash: boolean) { + const base = reading === 'en' ? config.value.enPrefix + '/' : '/'; + const pages = config.value.pages['root'] ?? []; + if (!pages.includes(current.value.page)) + return base; + return pageUrl(base, current.value.page) + (keepHash ? hash.value : ''); + } + + const isZh = computed(() => current.value.reading === 'zh'); + + const readingLanguages = computed(() => READING_LANGUAGES.map(reading => ({ + text: reading.text, + lang: reading.lang, + link: linkFor(reading.key, true), + active: reading.key === current.value.reading, + }))); + + const labels = computed(() => isZh.value + ? { menu: '切换语言', reading: '阅读语言' } + : { menu: 'Change language', reading: 'Language' }); + + const currentLabel = computed(() => + READING_LANGUAGES.find(reading => reading.key === current.value.reading)!.text); + + return { readingLanguages, labels, currentLabel, isZh }; +} diff --git a/.vitepress/theme/react/components.ts b/.vitepress/theme/react/components.ts new file mode 100644 index 0000000..a105d28 --- /dev/null +++ b/.vitepress/theme/react/components.ts @@ -0,0 +1,396 @@ +// Vue versions of the react.dev MDX components (react.dev: src/components/MDX/MDXComponents.tsx). +// scripts/import-react.mjs keeps the component tags in the pages; they are registered globally in ../index.ts. +// Interactive parts become static: is converted to a code group by the importer, +// challenges show hints and solutions in
, deep dives are always expanded. +import { computed, defineComponent, h, onMounted, ref, watch, type Component, type VNode } from 'vue'; +import { useData, useRoute, withBase } from 'vitepress'; + +type Labels = { zh: string; en: string }; + +function useLanguage() { + const { page, lang } = useData(); + const isZh = computed(() => lang.value.startsWith('zh')); + const isEnglishPage = computed(() => page.value.relativePath.startsWith('en/')); + // Links in component props are written against the Chinese site (root); English pages live under /en/. + const localize = (link?: string) => { + if (!link || !link.startsWith('/') || link.startsWith('//') || link.startsWith('/images/')) return link; + return withBase(isEnglishPage.value ? `/en${link}` : link); + }; + const t = (labels: Labels) => (isZh.value ? labels.zh : labels.en); + return { isZh, localize, t }; +} + +const wrapper = (tag: string, className: string) => defineComponent({ + setup(_, { slots }) { + return () => h(tag, { class: className }, slots.default?.()); + }, +}); + +function callout(type: string, title: Labels) { + return defineComponent({ + setup(_, { slots }) { + const { t } = useLanguage(); + return () => h('div', { class: `react-callout react-callout-${type}` }, [ + h('p', { class: 'react-callout-title' }, t(title)), + h('div', { class: 'react-callout-body' }, slots.default?.()), + ]); + }, + }); +} + +function badge(type: string, label: Labels) { + return defineComponent({ + props: { title: String }, + setup(props) { + const { t } = useLanguage(); + return () => h('span', { class: `react-badge react-badge-${type}`, title: props.title }, t(label)); + }, + }); +} + +function disclosure(className: string, label: Labels) { + return defineComponent({ + setup(_, { slots }) { + const { t } = useLanguage(); + return () => h('details', { class: className }, [ + h('summary', t(label)), + h('div', { class: `${className}-body` }, slots.default?.()), + ]); + }, + }); +} + +const YouWillLearn = defineComponent({ + props: { isChapter: Boolean }, + setup(props, { slots }) { + const { t } = useLanguage(); + return () => h('div', { class: 'react-box react-you-will-learn' }, [ + h('p', { class: 'react-box-title' }, props.isChapter + ? t({ zh: '本章节', en: 'In this chapter' }) + : t({ zh: '你将会学习到', en: 'You will learn' })), + slots.default?.(), + ]); + }, +}); + +const Recap = defineComponent({ + setup(_, { slots }) { + const { t } = useLanguage(); + return () => h('div', { class: 'react-box react-recap' }, [ + h('h3', { id: 'recap', class: 'react-box-title' }, t({ zh: '摘要', en: 'Recap' })), + slots.default?.(), + ]); + }, +}); + +const DeepDive = defineComponent({ + setup(_, { slots }) { + const { t } = useLanguage(); + return () => h('div', { class: 'react-deep-dive' }, [ + h('p', { class: 'react-deep-dive-label' }, t({ zh: '深入探讨', en: 'Deep Dive' })), + slots.default?.(), + ]); + }, +}); + +function challengeList(isRecipes: boolean) { + return defineComponent({ + props: { titleText: String, titleId: String, noTitle: Boolean }, + setup(props, { slots }) { + const { t } = useLanguage(); + const title = computed(() => props.titleText ?? (isRecipes + ? t({ zh: '尝试一些示例', en: 'Try out some examples' }) + : t({ zh: '尝试一些挑战', en: 'Try out some challenges' }))); + return () => { + const children: (VNode | VNode[] | undefined)[] = []; + if (!props.noTitle) { + children.push(isRecipes + ? h('p', { class: 'react-challenges-title', id: props.titleId }, title.value) + : h('h2', { class: 'react-challenges-title', id: props.titleId ?? 'challenges' }, title.value)); + } + children.push(slots.default?.()); + return h('div', { class: isRecipes ? 'react-recipes' : 'react-challenges' }, children); + }; + }, + }); +} + +const LearnMore = defineComponent({ + props: { path: String }, + setup(props, { slots }) { + const { t, localize } = useLanguage(); + return () => h('div', { class: 'react-box react-learn-more' }, [ + slots.default?.(), + props.path && h('a', { class: 'react-button', href: localize(props.path) }, t({ zh: '阅读更多', en: 'Read More' })), + ]); + }, +}); + +const YouWillLearnCard = defineComponent({ + props: { title: String, path: String }, + setup(props, { slots }) { + const { t, localize } = useLanguage(); + return () => h('div', { class: 'react-box react-card' }, [ + h('p', { class: 'react-box-title' }, props.title), + slots.default?.(), + props.path && h('a', { class: 'react-button', href: localize(props.path) }, t({ zh: '阅读更多', en: 'Read More' })), + ]); + }, +}); + +const ReadBlogPost = defineComponent({ + props: { name: String, path: String }, + setup(props, { slots }) { + const { t, localize } = useLanguage(); + return () => h('a', { class: 'react-button', href: localize(props.path) }, + slots.default?.() ?? t({ zh: '阅读文章', en: 'Read the post' })); + }, +}); + +const Diagram = defineComponent({ + props: { + name: { type: String, required: true }, + alt: String, + height: [Number, String], + width: [Number, String], + captionPosition: String, + }, + setup(props, { slots }) { + return () => { + const src = `/images/docs/diagrams/${props.name}`; + const size = { width: props.width, height: props.height }; + const caption = slots.default && h('figcaption', slots.default()); + return h('figure', { class: 'react-diagram' }, [ + props.captionPosition === 'top' ? caption : null, + h('img', { class: 'react-light-only', src: withBase(`${src}.png`), alt: props.alt, loading: 'lazy', ...size }), + h('img', { class: 'react-dark-only', src: withBase(`${src}.dark.png`), alt: props.alt, loading: 'lazy', ...size }), + props.captionPosition === 'top' ? null : caption, + ]); + }; + }, +}); + +const Illustration = defineComponent({ + props: { src: String, alt: String, caption: String, author: String, authorLink: String }, + setup(props) { + const { t } = useLanguage(); + return () => h('figure', { class: 'react-illustration' }, [ + h('img', { src: props.src && withBase(props.src), alt: props.alt, loading: 'lazy' }), + props.caption && h('figcaption', props.caption), + props.author && h('figcaption', { class: 'react-illustration-author' }, [ + t({ zh: '插图作者 ', en: 'Illustrated by ' }), + props.authorLink ? h('a', { href: props.authorLink, target: '_blank', rel: 'noreferrer' }, props.author) : props.author, + ]), + ]); + }, +}); + +const IllustrationBlock = defineComponent({ + props: { sequential: Boolean, author: String, authorLink: String }, + setup(props, { slots }) { + return () => h(props.sequential ? 'ol' : 'div', { + class: ['react-illustration-block', { 'react-illustration-sequential': props.sequential }], + }, slots.default?.().map(child => (props.sequential ? h('li', child) : child))); + }, +}); + +const CodeDiagram = defineComponent({ + props: { flip: Boolean }, + setup(props, { slots }) { + return () => h('div', { class: ['react-code-diagram', { 'react-code-diagram-flip': props.flip }] }, slots.default?.()); + }, +}); + +const ConsoleBlock = defineComponent({ + props: { level: { type: String, default: 'error' } }, + setup(props, { slots }) { + const { t } = useLanguage(); + return () => h('div', { class: 'react-console' }, [ + h('div', { class: 'react-console-header' }, t({ zh: '控制台', en: 'Console' })), + h('div', { class: `react-console-line react-console-${props.level}` }, slots.default?.()), + ]); + }, +}); + +const ConsoleBlockMulti = defineComponent({ + setup(_, { slots }) { + const { t } = useLanguage(); + return () => h('div', { class: 'react-console' }, [ + h('div', { class: 'react-console-header' }, t({ zh: '控制台', en: 'Console' })), + slots.default?.(), + ]); + }, +}); + +const ConsoleLogLine = defineComponent({ + props: { level: { type: String, default: 'info' } }, + setup(props, { slots }) { + return () => h('div', { class: `react-console-line react-console-${props.level}` }, slots.default?.()); + }, +}); + +const YouTubeIframe = defineComponent({ + props: { src: { type: String, required: true }, title: String }, + setup(props) { + return () => h('div', { class: 'react-video' }, h('iframe', { + src: props.src, + title: props.title ?? 'YouTube video player', + frameborder: '0', + allow: 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture', + allowfullscreen: true, + loading: 'lazy', + })); + }, +}); + +const TeamMember = defineComponent({ + props: { + name: String, title: String, permalink: String, photo: String, group: String, + github: String, twitter: String, threads: String, bsky: String, personal: String, + }, + setup(props, { slots }) { + return () => { + const links = [ + props.github && ['GitHub', `https://github.com/${props.github}`], + props.twitter && ['X', `https://x.com/${props.twitter}`], + props.threads && ['Threads', `https://threads.net/${props.threads}`], + props.bsky && ['Bluesky', `https://bsky.app/profile/${props.bsky}`], + props.personal && [props.personal, `https://${props.personal}`], + ].filter(Boolean) as [string, string][]; + return h('div', { class: 'react-team-member' }, [ + props.photo && h('img', { src: withBase(props.photo), alt: props.name, loading: 'lazy' }), + h('div', [ + h('h3', { id: props.permalink }, props.name), + h('p', { class: 'react-team-member-title' }, props.title), + h('p', slots.default?.()), + h('p', { class: 'react-team-member-links' }, links.map(([text, href]) => + h('a', { href, target: '_blank', rel: 'noreferrer' }, text))), + ]), + ]); + }; + }, +}); + +const BlogCard = defineComponent({ + props: { title: String, date: String, url: String, badge: Boolean }, + setup(props, { slots }) { + const { localize } = useLanguage(); + return () => h('a', { class: 'react-blog-card', href: localize(props.url) }, [ + h('p', { class: 'react-blog-card-title' }, props.title), + props.date && h('p', { class: 'react-blog-card-date' }, props.date), + h('div', { class: 'react-blog-card-excerpt' }, slots.default?.()), + ]); + }, +}); + +const CodeStep = defineComponent({ + props: { step: { type: [Number, String], default: 1 } }, + setup(props, { slots }) { + return () => h('span', { class: `react-code-step react-code-step-${props.step}` }, slots.default?.()); + }, +}); + +const MathI = defineComponent({ + setup(_, { slots }) { + return () => h('i', { class: 'react-math-i' }, slots.default?.()); + }, +}); + +// Lists the page's h2 headings (react.dev's ). +const InlineToc = defineComponent({ + setup() { + const route = useRoute(); + const headings = ref<{ id: string; text: string }[]>([]); + const collect = () => { + headings.value = Array.from(document.querySelectorAll('.vp-doc h2[id]')).map(el => ({ + id: el.id, + text: (el.textContent ?? '').replace(/​/g, '').replace(/#\s*$/, '').trim(), + })); + }; + onMounted(collect); + watch(() => route.path, () => setTimeout(collect)); + return () => h('ul', { class: 'react-inline-toc' }, headings.value.map(heading => + h('li', h('a', { href: `#${heading.id}` }, heading.text)))); + }, +}); + +const ErrorDecoder = defineComponent({ + setup() { + const { t } = useLanguage(); + return () => h('div', { class: 'react-callout react-callout-note' }, [ + h('p', [ + t({ + zh: '在生产环境的压缩版本中,React 不会发送完整的错误信息。完整的错误信息请在 ', + en: 'In the minified production build of React, full error messages are not sent. Look up the full message on ', + }), + h('a', { href: 'https://react.dev/errors', target: '_blank', rel: 'noreferrer' }, 'react.dev/errors'), + t({ zh: ' 查看。', en: '.' }), + ]), + ]); + }, +}); + +const LanguageList = defineComponent({ + setup() { + const { t } = useLanguage(); + return () => h('p', [ + t({ zh: '各语言版本列表请见 ', en: 'See the list of translations on ' }), + h('a', { href: 'https://translations.react.dev/', target: '_blank', rel: 'noreferrer' }, 'translations.react.dev'), + t({ zh: '。', en: '.' }), + ]); + }, +}); + +// Pages with live sandboxes are converted to code groups; these remain only as fallbacks. +const SandpackFallback = wrapper('div', 'react-sandpack'); + +export const reactComponents: Record = { + Intro: wrapper('div', 'react-intro'), + YouWillLearn, + Recap, + Note: callout('note', { zh: '注意', en: 'Note' }), + Pitfall: callout('pitfall', { zh: '陷阱', en: 'Pitfall' }), + Deprecated: callout('deprecated', { zh: '已废弃', en: 'Deprecated' }), + Wip: callout('wip', { zh: '正在建设中', en: 'Under Construction' }), + Canary: callout('canary', { zh: 'Canary', en: 'Canary' }), + RC: callout('canary', { zh: 'RC', en: 'RC' }), + Experimental: callout('experimental', { zh: '实验性功能', en: 'Experimental Feature' }), + NextMajor: callout('canary', { zh: 'React 19', en: 'React 19' }), + RSC: callout('rsc', { zh: 'React 服务器组件', en: 'React Server Components' }), + CanaryBadge: badge('canary', { zh: 'Canary', en: 'Canary' }), + ExperimentalBadge: badge('experimental', { zh: '实验性', en: 'Experimental' }), + NextMajorBadge: badge('canary', { zh: 'React 19', en: 'React 19' }), + RSCBadge: badge('rsc', { zh: 'RSC', en: 'RSC' }), + DeepDive, + Challenges: challengeList(false), + Recipes: challengeList(true), + Hint: disclosure('react-hint', { zh: '显示提示', en: 'Show hint' }), + Solution: disclosure('react-solution', { zh: '显示答案', en: 'Show solution' }), + LearnMore, + YouWillLearnCard, + ReadBlogPost, + Diagram, + DiagramGroup: wrapper('div', 'react-diagram-group'), + Illustration, + IllustrationBlock, + CodeDiagram, + FullWidth: wrapper('div', 'react-full-width'), + MaxWidth: wrapper('div', 'react-max-width'), + ConsoleBlock, + ConsoleBlockMulti, + ConsoleLogLine, + YouTubeIframe, + TeamMember, + BlogCard, + CodeStep, + Math: wrapper('span', 'react-math'), + MathI, + InlineToc, + ErrorDecoder, + LanguageList, + PackageImport: wrapper('div', 'react-package-import'), + Sandpack: SandpackFallback, + SandpackRSC: SandpackFallback, + SandpackWithHTMLOutput: SandpackFallback, +} satisfies Record; + diff --git a/.vitepress/theme/react/react.css b/.vitepress/theme/react/react.css new file mode 100644 index 0000000..10a2b15 --- /dev/null +++ b/.vitepress/theme/react/react.css @@ -0,0 +1,416 @@ +/* Styles for the react.dev components in ./components.ts. */ + +.vp-doc .react-intro { + font-size: 18px; + line-height: 1.7; + color: var(--vp-c-text-1); +} + +/* Boxes: You will learn, Recap, Learn more, Deep dive */ +.vp-doc .react-box, +.vp-doc .react-deep-dive { + margin: 24px 0; + border-radius: 12px; + padding: 16px 24px; + background-color: var(--vp-c-bg-soft); +} + +.vp-doc .react-you-will-learn, +.vp-doc .react-learn-more { + border: 1px solid var(--vp-c-brand-soft); + background-color: var(--vp-c-brand-soft); +} + +.vp-doc .react-box-title, +.vp-doc .react-deep-dive-label { + margin: 0 0 8px; + border: none; + padding: 0; + font-size: 16px; + font-weight: 700; + color: var(--vp-c-brand-1); +} + +.vp-doc .react-deep-dive { + border: 1px solid rgba(132, 92, 220, 0.3); + background-color: rgba(132, 92, 220, 0.08); +} + +.vp-doc .react-deep-dive-label { + text-transform: uppercase; + letter-spacing: 0.04em; + font-size: 13px; + color: #845cdc; +} + +.dark .vp-doc .react-deep-dive-label { + color: #b79bf0; +} + +/* Callouts: Note, Pitfall, Deprecated, Canary... */ +.vp-doc .react-callout { + margin: 24px 0; + border-left: 4px solid; + border-radius: 8px; + padding: 12px 20px; +} + +.vp-doc .react-callout-title { + margin: 0 0 4px; + font-weight: 700; +} + +.vp-doc .react-callout-note { + border-color: var(--vp-c-green-2); + background-color: var(--vp-c-green-soft); +} + +.vp-doc .react-callout-note .react-callout-title { + color: var(--vp-c-green-1); +} + +.vp-doc .react-callout-pitfall, +.vp-doc .react-callout-wip { + border-color: var(--vp-c-yellow-2); + background-color: var(--vp-c-yellow-soft); +} + +.vp-doc .react-callout-pitfall .react-callout-title, +.vp-doc .react-callout-wip .react-callout-title { + color: var(--vp-c-yellow-1); +} + +.vp-doc .react-callout-deprecated { + border-color: var(--vp-c-red-2); + background-color: var(--vp-c-red-soft); +} + +.vp-doc .react-callout-deprecated .react-callout-title { + color: var(--vp-c-red-1); +} + +.vp-doc .react-callout-canary, +.vp-doc .react-callout-experimental, +.vp-doc .react-callout-rsc { + border-color: var(--vp-c-purple-2); + background-color: var(--vp-c-purple-soft); +} + +.vp-doc .react-callout-canary .react-callout-title, +.vp-doc .react-callout-experimental .react-callout-title, +.vp-doc .react-callout-rsc .react-callout-title { + color: var(--vp-c-purple-1); +} + +.vp-doc .react-callout-body > :first-child, +.vp-doc .react-box > :nth-child(2), +.vp-doc .react-deep-dive > :nth-child(2) { + margin-top: 0; +} + +.vp-doc .react-callout-body > :last-child, +.vp-doc .react-box > :last-child, +.vp-doc .react-deep-dive > :last-child { + margin-bottom: 0; +} + +/* Badges */ +.vp-doc .react-badge { + display: inline-block; + margin: 0 2px; + border-radius: 6px; + padding: 0 6px; + font-size: 12px; + font-weight: 600; + line-height: 20px; + vertical-align: middle; + color: var(--vp-c-purple-1); + background-color: var(--vp-c-purple-soft); +} + +/* Challenges and examples */ +.vp-doc .react-challenges, +.vp-doc .react-recipes { + margin: 32px 0; + border: 1px solid var(--vp-c-divider); + border-radius: 12px; + padding: 0 24px 16px; +} + +.vp-doc .react-challenges-title { + margin: 0 -24px 16px; + border-top: none; + border-radius: 12px 12px 0 0; + padding: 16px 24px; + font-size: 20px; + font-weight: 700; + background-color: var(--vp-c-bg-soft); +} + +.vp-doc .react-challenges h4, +.vp-doc .react-recipes h4 { + margin-top: 32px; + border-top: 1px solid var(--vp-c-divider); + padding-top: 24px; + font-size: 18px; +} + +.vp-doc .react-challenges > h4:first-of-type, +.vp-doc .react-recipes > h4:first-of-type { + margin-top: 0; + border-top: none; + padding-top: 8px; +} + +.vp-doc details.react-hint, +.vp-doc details.react-solution { + margin: 16px 0; + border: 1px solid var(--vp-c-divider); + border-radius: 8px; + padding: 8px 16px; +} + +.vp-doc details.react-hint > summary, +.vp-doc details.react-solution > summary { + cursor: pointer; + font-weight: 600; + color: var(--vp-c-brand-1); +} + +.vp-doc details.react-solution[open] { + background-color: var(--vp-c-bg-soft); +} + +/* Links styled as buttons */ +.vp-doc a.react-button { + display: inline-block; + margin-top: 8px; + border-radius: 20px; + padding: 4px 16px; + font-weight: 600; + text-decoration: none; + color: var(--vp-c-white); + background-color: var(--vp-c-brand-1); +} + +.vp-doc a.react-button:hover { + background-color: var(--vp-c-brand-2); +} + +/* Diagrams and illustrations */ +.vp-doc .react-diagram, +.vp-doc .react-illustration { + margin: 24px auto; + text-align: center; +} + +.vp-doc .react-diagram img, +.vp-doc .react-illustration img { + display: inline-block; + max-width: 100%; + height: auto; +} + +.vp-doc .react-diagram figcaption, +.vp-doc .react-illustration figcaption { + margin-top: 8px; + font-size: 14px; + color: var(--vp-c-text-2); +} + +.react-dark-only, +.dark .react-light-only { + display: none !important; +} + +.dark .react-dark-only { + display: inline-block !important; +} + +.vp-doc .react-diagram-group, +.vp-doc .react-illustration-block { + display: flex; + flex-wrap: wrap; + justify-content: center; + align-items: flex-start; + gap: 16px; + margin: 24px 0; + padding: 0; +} + +.vp-doc .react-diagram-group > *, +.vp-doc .react-illustration-block > * { + flex: 1 1 200px; + margin: 0; +} + +.vp-doc .react-illustration-sequential { + list-style: decimal inside; +} + +.vp-doc .react-code-diagram { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + align-items: center; + gap: 16px; +} + +.vp-doc .react-code-diagram img { + display: block; + margin: 0 auto; + max-width: 100%; +} + +.vp-doc .react-package-import { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + gap: 16px; +} + +/* Console output */ +.vp-doc .react-console { + margin: 24px 0; + border: 1px solid var(--vp-c-divider); + border-radius: 8px; + overflow: hidden; + font-family: var(--vp-font-family-mono); + font-size: 13px; +} + +.vp-doc .react-console-header { + padding: 4px 12px; + font-weight: 600; + color: var(--vp-c-text-2); + background-color: var(--vp-c-bg-soft); +} + +.vp-doc .react-console-line { + border-top: 1px solid var(--vp-c-divider); + padding: 8px 12px; + overflow-x: auto; +} + +.vp-doc .react-console-line p { + margin: 0; +} + +.vp-doc .react-console-error { + color: var(--vp-c-red-1); + background-color: var(--vp-c-red-soft); +} + +.vp-doc .react-console-warning { + color: var(--vp-c-yellow-1); + background-color: var(--vp-c-yellow-soft); +} + +/* Videos */ +.vp-doc .react-video { + position: relative; + margin: 24px 0; + padding-top: 56.25%; +} + +.vp-doc .react-video iframe { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + border-radius: 8px; +} + +/* Team members */ +.vp-doc .react-team-member { + display: flex; + gap: 24px; + margin: 32px 0; +} + +.vp-doc .react-team-member img { + flex: none; + width: 120px; + height: 120px; + border-radius: 12px; + object-fit: cover; +} + +.vp-doc .react-team-member h3 { + margin: 0; +} + +.vp-doc .react-team-member p { + margin: 4px 0; +} + +.vp-doc .react-team-member-title { + color: var(--vp-c-text-2); +} + +.vp-doc .react-team-member-links a { + margin-right: 12px; +} + +@media (max-width: 640px) { + .vp-doc .react-team-member { + flex-direction: column; + gap: 12px; + } +} + +/* Blog cards */ +.vp-doc a.react-blog-card { + display: block; + margin: 16px 0; + border: 1px solid var(--vp-c-divider); + border-radius: 12px; + padding: 16px 20px; + text-decoration: none; + color: var(--vp-c-text-1); + transition: border-color 0.25s; +} + +.vp-doc a.react-blog-card:hover { + border-color: var(--vp-c-brand-1); +} + +.vp-doc .react-blog-card-title { + margin: 0; + font-size: 18px; + font-weight: 700; + color: var(--vp-c-brand-1); +} + +.vp-doc .react-blog-card-date { + margin: 4px 0 8px; + font-size: 13px; + color: var(--vp-c-text-2); +} + +.vp-doc .react-blog-card-excerpt p { + margin: 0; +} + +/* Highlighted code steps (react.dev's ) */ +.vp-doc .react-code-step { + border-bottom: 2px solid; + border-radius: 4px; + padding: 0 2px; + font-family: var(--vp-font-family-mono); + font-size: 0.9em; +} + +.vp-doc .react-code-step-1 { border-color: #087ea4; background-color: rgba(8, 126, 164, 0.12); } +.vp-doc .react-code-step-2 { border-color: #7c5ac9; background-color: rgba(124, 90, 201, 0.12); } +.vp-doc .react-code-step-3 { border-color: #d4600c; background-color: rgba(212, 96, 12, 0.12); } +.vp-doc .react-code-step-4 { border-color: #c43f6a; background-color: rgba(196, 63, 106, 0.12); } + +/* Inline math */ +.vp-doc .react-math { + font-family: Georgia, 'Times New Roman', serif; + font-size: 1.1em; + white-space: nowrap; +} + +.vp-doc .react-inline-toc { + margin: 16px 0; +} diff --git a/CNAME b/CNAME new file mode 100644 index 0000000..7a0fe07 --- /dev/null +++ b/CNAME @@ -0,0 +1 @@ +react.isharkfly.com \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..2f66313 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,158 @@ +pipeline { + agent any + + options { + ansiColor('xterm') + disableConcurrentBuilds() + // 文档约 460 页(中英文各约 230 页) + timeout(time: 30, unit: 'MINUTES') + } + + tools { + nodejs 'NodeJS 22.14.0' + } + + environment { + PRJ_NAME = 'react-isharkfly-com' + // 显式指定 wrangler 配置文件 + WRANGLER_CONFIG = 'wrangler.jsonc' + // 发布到线上的分支 + RELEASE_BRANCH = 'main' + // Worker Preview 的自定义预览域名 + PREVIEW_DOMAIN = 'react.sharkdat.com' + // Cloudflare API Token(Jenkins Secret text 凭据,需要 Workers Scripts:Edit 权限) + CLOUDFLARE_API_TOKEN = credentials('sharkdat-cloudflare-api-token') + // Cloudflare Account ID(Secret text 凭据)。设置后 wrangler 不再调用 /memberships 查询账号, + // 避免 token 缺少 Account 读取权限时报 "You may have incorrect permissions on your API token" + CLOUDFLARE_ACCOUNT_ID = credentials('sharkdat-cloudflare-account-id') + // 不让 wrangler 发送使用统计、不弹交互提示 + WRANGLER_SEND_METRICS = 'false' + CI = 'true' + } + + stages { + stage('Configure') { + steps { + sh 'git config --global url."https://github.com/".insteadOf git://github.com/' + sh ''' + set -eu + corepack enable + node --version + pnpm --version + ''' + } + } + + stage('Install') { + steps { + sh 'pnpm install --frozen-lockfile' + } + } + + stage('Build') { + steps { + echo 'Build VitePress docs ...' + // docs:build 会先生成侧边栏配置并组装中英文站点 site/(中文在根目录,英文在 /en/) + sh 'pnpm run docs:build' + } + } + + stage('Deploy - CF') { + steps { + script { + withEnv([ + 'LANG=C.UTF-8', + 'LC_ALL=C.UTF-8', + 'NO_COLOR=1', + 'TERM=dumb' + ]) { + // 部署消息:显示在 Cloudflare 控制台 → Worker → Deployments + def shortSha = env.GIT_COMMIT ? env.GIT_COMMIT.take(7) : 'unknown' + def deployMsg = "Jenkins ${env.JOB_NAME} #${env.BUILD_NUMBER} (${shortSha})" + + // Tag 构建:部署到 production 环境(wrangler.jsonc 中的 env.production) + if (env.TAG_NAME?.trim()) { + sh """ + pnpm exec wrangler deploy --config ${env.WRANGLER_CONFIG} --env production \ + --message '${deployMsg}' \ + --tag '${env.TAG_NAME}' + """ + return + } + + // main 分支:部署默认 Worker + if (env.BRANCH_NAME == env.RELEASE_BRANCH) { + sh """ + pnpm exec wrangler deploy --config ${env.WRANGLER_CONFIG} --env="" \ + --message '${deployMsg}' \ + --tag '${shortSha}' + """ + return + } + + // PR 或其他分支:创建/更新 Worker Preview,不影响线上流量 + // 访问地址:https://.react.sharkdat.com + // https://-react-isharkfly-com.huyuchengus.workers.dev + def branchArg = env.CHANGE_ID + ? "pr-${env.CHANGE_ID}" + : env.BRANCH_NAME + + // 转成合法的 DNS 标签:小写、只含 a-z0-9-,并限制长度 + // (- 也要放进一个 63 字符的子域名标签里) + def previewName = branchArg + .toLowerCase() + .replaceAll(/[^a-z0-9-]+/, '-') + .replaceAll(/^-+|-+$/, '') + previewName = previewName.take(40).replaceAll(/-+$/, '') + + // 打印当前 token 所属账号,便于排查 "Worker does not yet exist"(通常是账号不对) + sh 'pnpm exec wrangler whoami' + + // Preview 挂在已有 Worker 下;首次构建时先 deploy 一次创建 Worker + def workerExists = sh( + script: "pnpm exec wrangler deployments list --config ${env.WRANGLER_CONFIG} --env=\"\" > /dev/null 2>&1", + returnStatus: true + ) == 0 + if (!workerExists) { + echo "Worker ${env.PRJ_NAME} 尚不存在,先执行首次 deploy 创建 Worker ..." + sh """ + pnpm exec wrangler deploy --config ${env.WRANGLER_CONFIG} --env="" \ + --message 'Initial deploy: ${deployMsg}' + """ + } + + // 用新版 Previews(需要 wrangler >= 4.135.0),才会出现在自定义预览域名 react.sharkdat.com 下。 + // Jenkins 检出的是 detached HEAD,无法自动识别分支,所以必须显式传 --name。 + sh """ + pnpm exec wrangler preview --config ${env.WRANGLER_CONFIG} --env="" \ + --name '${previewName}' \ + --message '${deployMsg}' \ + --tag '${shortSha}' + """ + + echo "Preview URL: https://${previewName}.${env.PREVIEW_DOMAIN}" + } + } + } + } + } + + post { + always { + script { + env.BUILD_STARTED_AT = new Date(currentBuild.startTimeInMillis) + .format('yyyy-MM-dd HH:mm:ss z', TimeZone.getTimeZone('America/New_York')) + + env.BUILD_DURATION_TEXT = currentBuild.durationString + + emailext ( + mimeType: 'text/html; charset=UTF-8', + subject: "Build ${currentBuild.currentResult}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'", + body: '${DEFAULT_CONTENT}', + from: 'postmaster@mail.sharkdat.com', + to: 'dev@sharkdat.com, dev@sharkdat.cn' + ) + } + } + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..0ec20c7 --- /dev/null +++ b/README.md @@ -0,0 +1,81 @@ +# React 中文文档 + +react.isharkfly.com 站点源码。站点合并了 [reactjs/react.dev](https://github.com/reactjs/react.dev)(英文原版)和 [reactjs/zh-hans.react.dev](https://github.com/reactjs/zh-hans.react.dev)(简体中文翻译),使用 [VitePress](https://vitepress.dev/) 构建,部署到 Cloudflare Workers Static Assets,项目结构与 Docsify-iSharkFly-Com 保持一致。 + +- 中文(默认):`/<路径>` +- 英文原文:`/en/<路径>` + +## 目录结构 + +``` +├── src/ 英文原文(来自 react.dev 的 src/content/,不要手动修改) +│ └── public/ 静态资源(images/、favicon、logo.svg) +├── i18n/ +│ ├── zh/ 中文译文(来自 zh-hans.react.dev),与 src/ 路径一一对应 +│ └── TRANSLATION-GUIDE.md 翻译规范 +├── scripts/ +│ ├── import-react.mjs 从 react.dev 和 zh-hans.react.dev 导入页面和侧边栏(nav.json) +│ ├── nav.json 侧边栏(英文标题 text,中文标题 zh),由 import-react.mjs 生成 +│ ├── generate.mjs 生成 .vitepress/generated/site.json +│ └── sync-zh.mjs 组装 site/:中文放在根路径,英文放在 site/en/ +├── site/ 构建时生成(git 忽略) +├── .vitepress/ +│ ├── config.mts VitePress 配置 +│ └── theme/ 主题:语言切换、未翻译提示、react.dev 组件(theme/react/) +├── package.json 依赖与构建脚本(pnpm) +├── wrangler.jsonc Cloudflare 部署配置 +└── Jenkinsfile CI:构建并部署到 Cloudflare +``` + +## 本地开发 + +使用 pnpm 管理依赖(与 Jenkins 一致,Node 22 下先执行 `corepack enable`): + +```bash +pnpm install +pnpm run docs:dev # 本地预览(会先运行 generate.mjs 和 sync-zh.mjs) +pnpm run docs:build # 构建到 .vitepress/dist(约 450 页,需要 5 分钟左右) +``` + +修改 `src/` 或 `i18n/zh/` 后需要重新运行 `pnpm run docs:prepare`(或重启 `docs:dev`)。 + +> 页面较多,`docs:build` 用 `--max-old-space-size=16384` 提高了 Node 的内存上限,否则会内存溢出。 +> +> Windows 下请在盘符为大写的路径中运行(例如 `D:\WorkDir\...`),否则 VitePress 构建会报 `Cannot read properties of undefined (reading 'imports')`。 + +## 更新原文和译文 + +```bash +git clone --depth 1 https://github.com/reactjs/react.dev.git /tmp/react.dev +git clone --depth 1 https://github.com/reactjs/zh-hans.react.dev.git /tmp/zh-hans.react.dev +node scripts/import-react.mjs /tmp/react.dev /tmp/zh-hans.react.dev +``` + +导入脚本会: + +- 把 react.dev 的 `src/content/` 写入 `src/`,`public/images` 和图标写入 `src/public/`,`src/sidebar*.json` 转成 `scripts/nav.json`(中文标题取自 zh-hans.react.dev 的同名侧边栏)。 +- 把 zh-hans.react.dev 中**已翻译**的页面写入 `i18n/zh/`。正文(代码块以外)汉字少于 50 个的页面视为未翻译,跳过;这些页面在中文站显示英文原文和「本页尚未翻译」提示。zh-hans 目前不翻译博客,所以博客大多显示英文。 +- 把 react.dev 的 MDX 语法转换为 VitePress 可用的 Markdown: + - 标题 `## 标题 {/*id*/}` 转为 `## 标题 {#id}`,删除 `{/* 注释 */}`; + - `` 交互示例转为 `::: code-group` 代码组(每个可见文件一个标签页,`hidden` 文件不显示)。站点上是静态代码,不能在线运行; + - `` 转为 `bash` 代码块; + - JSX 属性 `x={...}` 转为 Vue 绑定 `:x="..."`,`className` 转为 `class`; + - 代码块信息中 react.dev 专用的 `[[1, 2, "x"]]`、`{expectedErrors: ...}` 被删除,行高亮 `{2-3}` 保留; + - frontmatter 的 `title` 生成页面一级标题(react.dev 由布局渲染标题)。 +- 首页(`index.md`)在 react.dev 中由 React 组件渲染,这里改用脚本内置的 VitePress 首页模板。 + +其余 react.dev 组件(``、``、``、``、``、``、``、``、`` 等)保留在页面中,由 `.vitepress/theme/react/components.ts` 实现为 Vue 组件,标签文字随页面语言切换。 + +构建时如果 `sync-zh.mjs` 输出 `anchors not aligned` 警告,说明 zh-hans 的译文落后于英文原文(标题数量不同)。react.dev 的标题都带有显式锚点 `{#id}`,所以锚点链接不受影响。 + +## 部署 + +Jenkins 多分支流水线(见 `Jenkinsfile`): + +- `main` 分支:部署到 Worker `react-isharkfly-com` +- Tag:部署到 `production` 环境 +- 其他分支 / PR:上传 Preview 版本(`https://<分支名>.react.sharkdat.com`) + +## 许可证 + +React 文档内容基于 [CC BY 4.0](https://github.com/reactjs/react.dev/blob/main/LICENSE-DOCS.md) 许可证发布,示例代码基于 MIT 许可证发布。 diff --git a/i18n/TRANSLATION-GUIDE.md b/i18n/TRANSLATION-GUIDE.md new file mode 100644 index 0000000..6b2034e --- /dev/null +++ b/i18n/TRANSLATION-GUIDE.md @@ -0,0 +1,23 @@ +# React 文档中文翻译规范 + +## 文件位置 + +- 英文原文:`src/<路径>.md`,**不要修改**。构建时 `scripts/sync-zh.mjs` 会把它发布到 `/en/<路径>`。 +- 中文译文:`i18n/zh/<路径>.md`,与原文路径一一对应。构建时发布到站点根路径 `/<路径>`。 +- 没有译文的页面会自动以英文显示并标记 `untranslated: true`。 +- 译文主要来自 [zh-hans.react.dev](https://github.com/reactjs/zh-hans.react.dev),由 `scripts/import-react.mjs` 导入。重新导入会覆盖 `i18n/zh/`,所以本地补充的译文最好也提交到 zh-hans.react.dev,或者在重新导入后检查差异。 + +## 翻译要求 + +1. 读者是中文开发者。译文要自然、通顺,不要逐词硬译;使用简体中文。 +2. **术语**与 zh-hans.react.dev 已有译文保持一致。例如:组件(Component)、属性(Props)、状态(State)、副作用(Effect)、渲染(Render)、提交(Commit)、引用(Ref)、上下文(Context)、服务器组件(Server Components)。 +3. 产品名、库名、API 名称和代码标识符保持英文:React、React DOM、Hook 名称(`useState`、`useEffect`)、``、`createRoot` 等。 +4. **不翻译**:代码块内的代码、行内代码(反引号内)、文件路径、命令、URL、HTML 标签和属性。代码块中的**注释**和界面文字可以翻译。 +5. **保持结构**:标题层级、列表、表格、`::: code-group` 代码组、react.dev 组件标签(``、``、``、``、``、``、`` 等)、空行和 frontmatter 的键名都保持原样。 + - 组件的标题(「注意」「陷阱」「深入探讨」「显示答案」等)由主题自动显示,不要写进正文。 + - ``、`` 的 `alt`、`caption` 属性要翻译;`name`、`src` 等属性保持原样。 +6. **链接**:链接地址保持原样(站内的 `/xxx` 链接会自动指向中文页面),只翻译链接文字。锚点链接(`#some-heading`)保持原样。 + - react.dev 的每个标题都带有英文锚点 `{#english-slug}`,**翻译标题时保留锚点不变**,这样英文页面上的 `#锚点` 链接在中文页面上同样有效。 + - 没有锚点的标题由 `scripts/sync-zh.mjs` 按顺序与英文标题配对,自动加上英文锚点。因此**译文的标题数量和顺序必须与原文完全一致**。构建时如果输出 `anchors not aligned` 警告,说明该页译文的标题数量与原文不一致。 +7. 中英文之间、中文与数字之间加一个空格。中文语境下使用全角标点(,。:;?!「」()),代码和英文内容中保持半角。 +8. 不要增删内容,不要添加译者注,除非原文有明显错误。 diff --git a/i18n/zh/blog/2020/12/21/data-fetching-with-react-server-components.md b/i18n/zh/blog/2020/12/21/data-fetching-with-react-server-components.md new file mode 100644 index 0000000..62417d8 --- /dev/null +++ b/i18n/zh/blog/2020/12/21/data-fetching-with-react-server-components.md @@ -0,0 +1,36 @@ +--- +title: "介绍零打包大小的 React 服务器组件" +author: Dan Abramov, Lauren Tan, Joseph Savona, and Sebastian Markbage +date: 2020/12/21 +description: 2020 年是漫长的一年。随着它的结束,我们想在节日里分享一份特别的更新,介绍我们对零打包大小的 React 服务器组件的研究。 +--- + +# 介绍零打包大小的 React 服务器组件 {#page-title} + +2020 年 12 月 21 日 [Dan Abramov](https://bsky.app/profile/danabra.mov)、[Lauren Tan](https://twitter.com/potetotes)、[Joseph Savona](https://twitter.com/en_JS) 与 [Sebastian Markbåge](https://twitter.com/sebmarkbage) + +--- + + + +2020 年是漫长的一年。随着它的结束,我们想在节日里分享一份特别的更新,介绍我们对零打包大小的 **React 服务器组件** 的研究。 + + + +--- + +为了介绍 React 服务器组件,我们准备了一次演讲和演示。如果你愿意,在假期期间或新年工作重新开始后查看它们。 + + + +**React 服务器组件仍处于研究和开发阶段**。我们将以透明的精神分享这项工作,并希望从 React 社区获得初步反馈。这个过程需要很多时间,所以 **你现在不必急着赶上进展**! + +如果你想了解它们,我们建议按照以下顺序进行查看: + +1. **观看演讲** 以了解 React 服务器组件并观看演示。 + +2. **[克隆演示](http://github.com/reactjs/server-components-demo)** 并在你的计算机上尝试使用 React 服务器组件。 + +3. **[阅读 RFC(文末有FAQ)](https://github.com/reactjs/rfcs/pull/188)** 以深入了解技术细节并提供反馈意见。 + +我们非常期待你对 RFC 的反馈或者通过 [@reactjs](https://twitter.com/reactjs) 的 Twitter 账号回复我们。祝你度过愉快的假期,保重,明年再见! diff --git a/i18n/zh/blog/2021/06/08/the-plan-for-react-18.md b/i18n/zh/blog/2021/06/08/the-plan-for-react-18.md new file mode 100644 index 0000000..00616bb --- /dev/null +++ b/i18n/zh/blog/2021/06/08/the-plan-for-react-18.md @@ -0,0 +1,73 @@ +--- +title: "React 18 的有关计划" +author: Andrew Clark, Brian Vaughn, Christine Abernathy, Dan Abramov, Rachel Nabors, Rick Hanlon, Sebastian Markbage, and Seth Webster +date: 2021/06/08 +description: React 团队很高兴分享一些更新。我们已经开始推进 React 18 的更新,也正是我们的下一个主要版本。我们已经创建了一些工作组,筹备 React 18 新功能在社区内逐步推广的相关工作。我们已经发布了一个 React 18 Alpha 版本,以便于一些库的作者们能够测试并反馈…… +--- + +# React 18 的有关计划 {#page-title} + +2021 年 7 月 8 日 [Andrew Clark](https://twitter.com/acdlite)、[Brian Vaughn](https://github.com/bvaughn)、[Christine Abernathy](https://twitter.com/abernathyca)、[Dan Abramov](https://bsky.app/profile/danabra.mov)、[Rachel Nabors](https://twitter.com/rachelnabors)、[Rick Hanlon](https://twitter.com/rickhanlonii)、[Sebastian Markbåge](https://twitter.com/sebmarkbage) 与 [Seth Webster](https://twitter.com/sethwebster) + +--- + + + +React 团队很高兴分享一些更新: + +1. 我们已经开始推进 React 18 的更新,也正是我们的下一个主要版本。 +2. 我们已经创建了一些工作组,筹备 React 18 新功能在社区内逐步推广的相关工作。 +3. 我们已经发布了一个 React 18 Alpha 版本,以便于一些库的作者们能够测试并反馈。 + +这些更新主要针对于第三方库的维护者们。如果你正在学习,教授或者使用 React 来构建面向用户的应用程序,你可以忽略这篇文章。但是如果你对此感到好奇,我们也非常欢迎你关注 React 18 工作组中的讨论。 + +--- + + + +## React 18 带来了什么 {#whats-coming-in-react-18} + +当 React 18 发布时,它将会有更好的开箱即用能力(如 [自动批处理](https://github.com/reactwg/react-18/discussions/21)),全新的 API(如 [`startTransition`](https://github.com/reactwg/react-18/discussions/41)),以及支持 `React.lazy` 的 [全新的流式服务端渲染](https://github.com/reactwg/react-18/discussions/37)。 + +这些功能之所以能够实现,要归功于我们在 React 18 中新加入的可选择性启用的机制,“并发渲染”,并且它使得 React 可以同时准备多个版本的 UI。这些大部分都是对底层的改动,但是也为你的应用程序提高其真实性能和用户感知性能创造了新的可能性, + +如果你一直在关注我们对 React 的未来的研究(我们并不希望你这么做!),你可能已经听说过“并发模式”,或许还听说过它可能会对你的应用程序造成破坏性变更。为了回应社区对此的反馈,我们已经重新设计了渐进式的升级策略。相比于之前要么不升级,要么全部升级这样一刀切的方式,现在的只有被并发渲染相关的新功能触发的更新才会启用并发渲染。这对于工程实践的意义是,**你无需重写代码即可直接使用 React 18,并且可以根据自己的节奏和需求来尝试新特性**。 + +## 渐进式应用策略 {#a-gradual-adoption-strategy} + +由于并发机制在 React 18 中是一个可选功能,没有对组件行为造成明显的破坏性变更。**你几乎不需要对应用程序中的代码进行任何改动,就可以直接升级到 React 18,这比以往的 React 版本升级要容易许多**。根据我们自己将几个应用程序升级到 React 18 的经验来看,预计大多数用户能在一个下午的时间内完成升级工作。 + +我们在 Facebook 上成功地将并发功能赋予给了数以万计的组件,并且以我们的实践经验来看,大部分的 React 组件无需任何改动就能正常工作。今天我们成立了 React 18 工作组,我们将致力于保证整个社区都能顺利升级。 + +## 与社区合作 {#working-with-the-community} + +在这次更新中,我们正在尝试一些新的可能:我们邀请了 React 社区的专家、开发者、库的作者以及教育者参与我们的 [React 18 工作组](https://github.com/reactwg/react-18),以提供反馈,咨询问题以及参与版本更新。我们没有没办法将所有人都邀请到这个刚建立的小群体,但是如果这次试验成功的话,我们也期待更多人的加入。 + +**React 18 工作组的目标是为生态做好准备,使现有的应用程序和库能够顺利、渐进地采用 React 18**。该工作组被托管在 [GitHub 讨论区](https://github.com/reactwg/react-18/discussions) 以供公众阅读。工作组的成员也可以留下反馈,咨询问题以及分享想法。核心团队也将会使用这个代码仓库的讨论区来分享我们的研发成果。在新版本变得越来越稳定的同时,所有重要信息都会在博客上发布。 + +想要了解关于升级到 React 18 的更多信息,或者关于该版本的其他资源,请参阅 [React 18 公告](https://github.com/reactwg/react-18/discussions/4)。 + +## 访问 React 18 工作组 {#accessing-the-react-18-working-group} + +每个人都可以阅读在 [React 18 工作组代码仓库](https://github.com/reactwg/react-18) 中的讨论信息。 + +我们预计对工作组感兴趣的人数会激增,所以目前只允许被邀请的成员可以创建或评论主题。不过,这些过程是完全公开的,所以每个人都能得到一致的信息。我们相信这是一个很好的折衷方案,既能为工作组的成员创造一个利于工作的环境,又能保持对广大社区的开放性。 + +和从前一样,你仍然可以在我们的 [issue](https://github.com/facebook/react/issues) 中发布错误报告、疑难问题和反馈等信息。 + +## 如何体验 React 18 alpha {#how-to-try-react-18-alpha-today} + +新的 alpha 版本是 [将 `@alpha` 标签定期发布到 npm 中](https://github.com/reactwg/react-18/discussions/9)。这些版本是由我们仓库主分支上最新的提交内容构建的。当一个新功能或者漏洞补丁被合并到主分支时,这些内容将在下一个工作日中出现在 alpha 版本中。 + +在 alpha 版本之间可能会有重大的行为逻辑或者 API 的变动。请谨记,**alpha 版本不建议在面向用户的生产环境应用中使用**。 + +## React 18 的预计发布时间 {#projected-react-18-release-timeline} + +我们没有明确的版本更新排期,但是我们预计在 React 18 可以满足大部分的生产环境应用之前,需要几个月的时间来收集反馈和迭代更新。 + +* 库的 Alpha 版本:今天可用 +* 公开的 Beta 版:至少几个月 +* RC 版本:至少在 Beta 版发布后的几周 +* 正式版:至少在 RC 版本发布之后的几周 + +关于发布任务排期的更多细节都在 [走近工作组](https://github.com/reactwg/react-18/discussions/9)。当临近公开发布时,我们会在这个博客上发布更新。 diff --git a/i18n/zh/blog/2021/12/17/react-conf-2021-recap.md b/i18n/zh/blog/2021/12/17/react-conf-2021-recap.md new file mode 100644 index 0000000..dfde617 --- /dev/null +++ b/i18n/zh/blog/2021/12/17/react-conf-2021-recap.md @@ -0,0 +1,162 @@ +--- +title: "回顾 React Conf 2021" +author: Jesslyn Tannady and Rick Hanlon +date: 2021/12/17 +description: 上周,我们举办了第六届 React Conf。在以往的几年中,我们在 React Conf 的舞台上发布了行业改变的信息,如 React Native 和 React Hooks。今年,我们从发布 React 18 和逐步采用并发功能开始,分享了我们对 React 的多平台愿景。 +--- + +# 回顾 React Conf 2021 {#page-title} + +2021 年 12 月 17 日 [Jesslyn Tannady](https://twitter.com/jtannady) 与 [Rick Hanlon](https://twitter.com/rickhanlonii) + +--- + + + +上周,我们举办了第六届 React Conf。在以往的几年中,我们在 React Conf 的舞台上发布了行业改变的信息,如 [**React Native**](https://engineering.fb.com/2015/03/26/android/react-native-bringing-modern-web-techniques-to-mobile/) 和 [**React Hooks**](https://reactjs.org/docs/hooks-intro.html)。今年,我们从发布 React 18 和逐步采用并发功能开始,分享了我们对 React 的多平台愿景。 + + + +--- + +这是 React Conf 首次在线举办,并且免费直播,并翻译成 8 种不同的语言。来自世界各地的参与者参加了我们的会议 Discord 和针对所有时区都可访问的重播活动。超过 50000 人注册,19 场演讲总共有超过 60000 次观看,Discord 平台上两个活动共有 5000 名参与者。 + +所有的演讲都可以 [在线播放](https://www.youtube.com/watch?v=FZ0cG47msEk&list=PLNG_1j3cPCaZZ7etkzWA7JfdmKWT0pMsa)。 + +以下是大会分享内容的摘要: + +## React 18 和并发特性 {#react-18-and-concurrent-features} + +在主题演讲中,我们分享了从 React 18 开始对未来 React 的愿景。 + +在没有引入任何重大的破坏性变化的情况下,React 18 添加了期待已久的并发渲染器和对 Suspense 的更新。应用程序可以升级到 React 18 并开始逐步采用并发功能,其工作量与任何其他主要版本相当。 + +**这意味着没有并发模式,只有并发功能**。 + +在主题演讲中,我们还分享了对 Suspense、服务器组件、新 React 工作组的愿景,以及对 React Native 的长期多平台愿景。 + +请在此处观看 [Andrew Clark](https://twitter.com/acdlite)、[Juan Tejada](https://twitter.com/_jstejada)、[Lauren Tan](https://twitter.com/potetotes) 和 [Rick Hanlon](https://twitter.com/rickhanlonii) 的完整主题演讲: + + + +## 面向应用程序开发人员的 React 18 {#react-18-for-application-developers} + +在主题演讲中,我们还宣布 React 18 RC 现已可供试用。在等待进一步的反馈之前,这是我们将于明年初发布稳定版的 React 版本。 + +要尝试 React 18 RC,请升级你的依赖项: + +```bash +npm install react@rc react-dom@rc +``` + +并切换到新的 **createRoot** API: + +```js +// 切换前 +const container = document.getElementById('root'); +ReactDOM.render(, container); + +// 切换后 +const container = document.getElementById('root'); +const root = ReactDOM.createRoot(container); +root.render(); +``` + +有关升级到 React 18 的演示,请参阅 [Shruti Kapoor](https://twitter.com/shrutikapoor08) 的演讲: + + + +## Suspense 串流服务端渲染 {#streaming-server-rendering-with-suspense} + +React 18 还包括使用 Suspense 对服务端渲染性能的改进。 + +串流服务端渲染允许你从服务器上的 React 组件生成 HTML,并将该 HTML 流式传输给用户。在 React 18 中,你可以使用 **Suspense** 将应用程序分解为更小的独立单元,这些单元可以彼此独立地进行流式传输,而不会阻塞应用程序的其余部分。这意味着用户将更快地看到你的内容,并能够更快地开始与之交互。 + +如需深入了解,请参阅 [Shaundai Person](https://twitter.com/shaundai) 的演讲: + + + +## 第一个 React 工作组 {#the-first-react-working-group} + +对于 React 18,我们创建了第一个工作组,与专家、开发人员、库维护人员和教育工作者小组合作。我们共同制定了逐步采用策略并完善了新的 API,例如 **useId**、**useSyncExternalStore** 和 **useInsertionEffect**。 + +有关这项工作的概述,请参阅 [Aakansha' Doshi](https://twitter.com/aakansha1216) 的演讲: + + + +## React 开发者工具 {#react-developer-tooling} + +为了支持此版本中的新功能,我们还宣布了新成立的 React DevTools 团队和新的 Timeline Profiler,以帮助开发人员调试他们的 React 应用程序。 + +有关新 DevTools 功能的更多信息和演示,请参阅 [Brian Vaughn](https://twitter.com/brian_d_vaughn) 的演讲: + + + +## 没有 memo 的 React {#react-without-memo} + +展望未来,[Xuan Huang (黄玄)](https://twitter.com/Huxpro) 分享了我们的 React Labs 对自动记忆编译器的研究的更新。查看此演讲以获取更多信息和编译器原型的演示: + + + +## React 文档主题演讲 {#react-docs-keynote} + +[Rachel Nabors](https://twitter.com/rachelnabors) 开始了有关 React 学习和设计的部分演讲,并发表了关于我们对 React 新文档([现已作为 React.dev 发布](/blog/2023/03/16/introducing-react-dev))的投入的主题演讲: + + + +## 以及更多 {#and-more} + +**我们还听到了有关使用 React 进行学习和设计的演讲**: + +* 由 Debbie O'Brien 演讲的 [Things I learnt from the new React docs](https://youtu.be/-7odLW_hG7s)。 +* 由 Sarah Rainsberger 演讲的 [Learning in the Browser](https://youtu.be/5X-WEQflCL0)。 +* 由 Linton Ye 演讲的 [The ROI of Designing with React](https://youtu.be/7cPWmID5XAk)。 +* 由 Delba de Oliveira 演讲的 [Interactive playgrounds with React](https://youtu.be/zL8cz2W0z34)。 + +**来自 Relay、React Native 和 PyTorch 团队的演讲**: + +* 由 Robert Balicki 演讲的 [Re-introducing Relay](https://youtu.be/lhVGdErZuN4)。 +* 由 Eric Rozell 和 Steven Moyes 演讲的 [React Native Desktop](https://youtu.be/9L4FFrvwJwY)。 +* 由 Roman Rädle 演讲的 [On-device Machine Learning for React Native](https://youtu.be/NLj73vrc2I8)。 + +**社区中关于可访问性、工具和服务器组件的演讲**: + +* 由 Daishi Kato 演讲的 [React 18 for External Store Libraries](https://youtu.be/oPfSC5bQPR8)。 +* 由 Diego Haz 演讲的 [Building Accessible Components in React 18](https://youtu.be/dcm8fjBfro8)。 +* 由 Tafu Nakazaki 演讲的 [Accessible Japanese Form Components with React](https://youtu.be/S4a0QlsH0pU). +* 由 Lyle Troxell 演讲的 [UI tools for artists](https://youtu.be/b3l4WxipFsE)。 +* 由 Helen Lin 演讲的 [Hydrogen + React 18](https://youtu.be/HS6vIYkSNks)。 + +## 感谢 {#thank-you} + +这是我们自己策划会议的第一年,我们要感谢很多人。 + +首先,感谢所有演讲者 [Aakansha Doshi](https://twitter.com/aakansha1216),、 [Andrew Clark](https://twitter.com/acdlite)、[Brian Vaughn](https://twitter.com/brian_d_vaughn)、[Daishi Kato](https://twitter.com/dai_shi)、[Debbie O'Brien](https://twitter.com/debs_obrien)、[Delba de Oliveira](https://twitter.com/delba_oliveira)、[Diego Haz](https://twitter.com/diegohaz)、[Eric Rozell](https://twitter.com/EricRozell)、[Helen Lin](https://twitter.com/wizardlyhel)、[Juan Tejada](https://twitter.com/_jstejada)、[Lauren Tan](https://twitter.com/potetotes)、[Linton Ye](https://twitter.com/lintonye)、[Lyle Troxell](https://twitter.com/lyle)、[Rachel Nabors](https://twitter.com/rachelnabors)、[Rick Hanlon](https://twitter.com/rickhanlonii)、[Robert Balicki](https://twitter.com/StatisticsFTW)、[Roman Rädle](https://twitter.com/raedle)、[Sarah Rainsberger](https://twitter.com/sarah11918)、[Shaundai Person](https://twitter.com/shaundai)、[Shruti Kapoor](https://twitter.com/shrutikapoor08)、[Steven Moyes](https://twitter.com/moyessa)、[Tafu Nakazaki](https://twitter.com/hawaiiman0) 和 [Xuan Huang (黄玄)](https://twitter.com/Huxpro)。 + +感谢所有为会谈提供反馈的人,包括 [Andrew Clark](https://twitter.com/acdlite)、[Dan Abramov](https://bsky.app/profile/danabra.mov)、[Dave McCabe](https://twitter.com/mcc_abe)、[Eli White](https://twitter.com/Eli_White)、[Joe Savona](https://twitter.com/en_JS)、 [Lauren Tan](https://twitter.com/potetotes)、[Rachel Nabors](https://twitter.com/rachelnabors) 和 [Tim Yung](https://twitter.com/yungsters)。 + +感谢 [Lauren Tan](https://twitter.com/potetotes) 组织了 Discord 会议并担任我们的 Discord 管理员。 + +感谢 [Seth Webster](https://twitter.com/sethwebster) 对总体方向的反馈,并确保我们专注于多样性和包容性。 + +感谢 [Rachel Nabors](https://twitter.com/rachelnabors) 领导我们的审核工作,感谢 [Aisha Blake](https://twitter.com/AishaBlake) 创建我们的审核指南、领导我们的审核团队、培训翻译人员和审核人员以及帮助审核这两项活动。 + +感谢我们的会议主席 [Jesslyn Tannady](https://twitter.com/jtannady)、[Suzie Grange](https://twitter.com/missuze)、[Becca Bailey](https://twitter.com/beccaliz)、[Luna Wei](https://twitter.com/lunaleaps)、[Joe Previte](https://twitter.com/jsjoeio)、[Nicola Corti](https://twitter.com/Cortinico)、[Gijs Weterings](https://twitter.com/gweterings)、[Claudio Procida](https://twitter.com/claudiopro)、Julia Neumann、Mengdi Chen、Jean Zhang、Ricky Li 和 [Xuan Huang (黄玄)](https://twitter.com/Huxpro)。 + +感谢来自 [React India](https://www.reactindia.io/) 的 [Manjula Dube](https://twitter.com/manjula_dube)、[Sahil Mhapsekar](https://twitter.com/apheri0) 和 Vihang Patel,以及来自 [React China](https://twitter.com/ReactChina) 的 [Jasmine Xie](https://twitter.com/jasmine_xby)、[QiChang Li](https://twitter.com/QCL15) 和 [YanLun Li](https://twitter.com/anneincoding) 帮助主持我们的重播活动并保持其对社区的吸引力。 + +感谢 Vercel 发布了会议网站所基于的 [虚拟活动入门套件](https://vercel.com/virtual-event-starter-kit),并感谢 [Lee Robinson](https://twitter.com/leeerob) 和 [Delba de Oliveira](https://twitter.com/delba_oliveira) 分享了他们举办 Next.js Conf 的经验。 + +感谢 [Leah Silber](https://twitter.com/wifelette) 分享她举办会议的经验、从举办 [RustConf](https://rustconf.com/) 中学到的知识,以及她的书 [《事件驱动》](https://leanpub.com/eventdriven/) 及其包含的关于举办会议的建议。 + +感谢 [Kevin Lewis](https://twitter.com/_phzn) 和 [Rachel Nabors](https://twitter.com/rachelnabors) 分享了她们举办 Women of React Conf 的经验。 + +感谢 [Aakansha Doshi](https://twitter.com/aakansha1216)、[Laurie Barth](https://twitter.com/laurieontech)、[Michael Chan](https://twitter.com/chantastic) 和 [Shaundai Person](https://twitter.com/shaundai) 在整个规划过程中提供的建议和想法。 + +感谢 [Dan Lebowitz](https://twitter.com/lebo) 帮助设计和构建会议网站和门票。 + +感谢 Laura Podolak Waddell、Desmond Osei-Acheampong、Mark Rossi、Josh Toberman 以及 Facebook 视频制作团队的其他人员录制了主题演讲和 Meta 员工演讲的视频。 + +感谢我们的合作伙伴 HitPlay 帮助组织会议、编辑直播中的所有视频、翻译所有演讲以及以多种语言主持 Discord。 + +最后,感谢所有参与者让本次 React Conf 变得精彩! diff --git a/i18n/zh/blog/2022/03/08/react-18-upgrade-guide.md b/i18n/zh/blog/2022/03/08/react-18-upgrade-guide.md new file mode 100644 index 0000000..d1f26d8 --- /dev/null +++ b/i18n/zh/blog/2022/03/08/react-18-upgrade-guide.md @@ -0,0 +1,332 @@ +--- +title: "如何升级到 React 18" +author: Rick Hanlon +date: 2022/03/08 +description: 正如我们在发布报告中分享的那样,React 18 借助新的并发渲染引入了许多新特性,对于已经存在的应用可以采用渐进式策略。在这篇文章中,我们会指导你如何逐步升级到 React 18。 +--- + +# 如何升级到 React 18 {#page-title} + +2022 年 8 月 3 日 [Rick Hanlon](https://twitter.com/rickhanlonii) + +--- + + + +正如我们在 [发布报告](/blog/2022/03/29/react-v18) 中分享的那样,React 18 借助新的并发渲染引入了许多新特性,对于已经存在的应用可以采用渐进式策略。在这篇文章中,我们会指导你如何逐步升级到 React 18。 + +如果你在升级的过程中遇到任何问题,可以在 GitHub [提 issue](https://github.com/facebook/react/issues/new/choose)。 + + + + + +对于 React Native 用户来说, React 18 会在 React Native 的未来版本中出现。因为 React 18 依赖于新的 React Native 架构才能受益于这篇文章中提出的新的能力。想了解更多信息,请查看 [这里的 React 会议纪要](https://www.youtube.com/watch?v=FZ0cG47msEk&t=1530s)。 + + + +--- + +## 安装 {#installing} + +安装最新版的 React: + +```bash +npm install react react-dom +``` + +或者也可以使用 yarn: + +```bash +yarn add react react-dom +``` + +## 客户端渲染 API 的更新 {#updates-to-client-rendering-apis} + +当你第一次安装 React 18 的时候,控制台会出现如下警告: + + + +ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot + + + +React 18 引入了一个新的 root API,它提供了更好的操作根节点的方式。新的 root API 还启用了新的并发渲染器,使开发者能够选择使用并发特性。 + +```js +// 之前 +import { render } from 'react-dom'; +const container = document.getElementById('app'); +render(, container); + +// 现在 +import { createRoot } from 'react-dom/client'; +const container = document.getElementById('app'); +const root = createRoot(container); // 如果你使用 TypeScript,请使用 createRoot(container!) +root.render(); +``` + +我们也已经将 `unmountComponentAtNode` 修改为 `root.unmount`: + +```js +// 之前 +unmountComponentAtNode(container); + +// 现在 +root.unmount(); +``` + +我们从 render 中移除了回调函数,因为当使用 Suspense 的时候通常不是预期的结果: + +```js +// 之前 +const container = document.getElementById('app'); +render(, container, () => { + console.log('rendered'); +}); + +// 现在 +function AppWithCallbackAfterRender() { + useEffect(() => { + console.log('rendered'); + }); + + return +} + +const container = document.getElementById('app'); +const root = createRoot(container); +root.render(); +``` + + + +对于旧的 render 回调函数 API 没有一对一的替换——它取决于你的用例。查看工作组的 [使用 createRoot 替换 render](https://github.com/reactwg/react-18/discussions/5) 博文了解更多信息。 + + + +最后如果应用通过激活使用了服务端渲染,你需要将 `hydrate` 升级到 `hydrateRoot`: + +```js +// 之前 +import { hydrate } from 'react-dom'; +const container = document.getElementById('app'); +hydrate(, container); + +// 现在 +import { hydrateRoot } from 'react-dom/client'; +const container = document.getElementById('app'); +const root = hydrateRoot(container, ); +// 和 createRoot 不一样,在这里你不需要单独的 root.render()。 +``` + +了解更多信息,请查看 [工作组的讨论](https://github.com/reactwg/react-18/discussions/5)。 + + + +**如果你的应用升级后无法工作,请检查它是否被 `` 包裹**。[严格模式在 React 18 中变得更加严格](#updates-to-strict-mode),并不是所有组件都可以弹性应对它在开发模式中添加的新检查。如果移除严格模式可以修复你的应用,你可以在升级期间移除它,然后等你修复它指出的问题之后再在树的顶部或者其中一部分添加回来。 + + + +## 服务端渲染 API 的更新 {#updates-to-server-rendering-apis} + +在这次发布中,我们修改 `react-dom/server` API 使它完全支持服务端的 Suspense 和 流式 SSR。作为这些变化的一部分,我们正在废弃旧的 Node 流式 API,因为它不支持服务端的增量 Suspense 流。 + +现在使用这个 API 会发出警告: + +* `renderToNodeStream`:**废弃 ⛔️️** + +取而代之的是,对于 Node 环境中的流我们使用: +* `renderToPipeableStream`:**新增 ✨** + +同时也引入了新的 API 借助 Suspense 为像 Deno 和 Cloudflare workers 这样的现代分布式运行时环境来支持流式 SSR: +* `renderToReadableStream`:**新增 ✨** + +下面的 API 会继续工作,但是对于 Suspense 支持是有限的: +* `renderToString`:**有限制** ⚠️ +* `renderToStaticMarkup`:**有限制** ⚠️ + +最后这个 API 会继续用于渲染电子邮件: +* `renderToStaticNodeStream` + +更多关于服务端渲染 API 的变化信息,可以查看工作组文章 [在服务端升级到 React 18](https://github.com/reactwg/react-18/discussions/22),[深入探讨新的 Suspense SSR 架构](https://github.com/reactwg/react-18/discussions/37),以及 [Shaundai 个人](https://twitter.com/shaundai) 在 React 2021 会议上关于 [使用 Suspense 的流式服务端渲染](https://www.youtube.com/watch?v=pj5N-Khihgc) 的演讲。 + +## 更新 TypeScript 类型定义 {#updates-to-typescript-definitions} + +如果项目使用了 TypeScript,你需要更新 `@types/react` 和 `@types/react-dom` 依赖到最新版。新的类型更加安全并且能捕获过去常常被类型检查器忽略的问题。最值得注意的变化是,现在定义 props 时,`children` prop 需要被明确列出来,例如: + +```typescript{3} +interface MyButtonProps { + color: string; + children?: React.ReactNode; +} +``` + +查看 [React 18 类型 PR](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210) 查看只有类型变了的完整清单。它链接到了在类型库中修复的例子,你可以从中了解如何调整你自己的代码。你可以使用 [自动迁移脚本](https://github.com/eps1lon/types-react-codemod) 来帮助你的应用代码更快变更到更安全的新类型。 + +如果你发现了类型中的问题,请在 DefinitelyTyped 仓库 [提交 issue](https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/new?category=issues-with-a-types-package)。 + +## 自动批处理 {#automatic-batching} + +React 18 通过默认做更多批量处理来增加开箱即用性能提升。批量处理指的是 React 为了提高性能将多个 state 更新分组到一个单独的重渲染。React 18 之前,我们只在 React 事件处理函数内部实现批量更新,而 promise、setTimeout、本地事件处理函数或者其他事件中更新状态,在 React 中默认是不进行批量处理的: + +```js +// React 18 之前,只有 React 事件会被批量处理 + +function handleClick() { + setCount(c => c + 1); + setFlag(f => !f); + // React 只会在结束的时候重新渲染一次(这就是批量处理!) +} + +setTimeout(() => { + setCount(c => c + 1); + setFlag(f => !f); + // React 会渲染两次,每一个 state 更新的时候渲染一次(非批量处理) +}, 1000); +``` + +从使用 `createRoot` 的 React 18 开始,无论来自于哪里,所有的更新都会自动批量处理。这意味着 timeout、promise、本地事件处理函数或者其他任何事件的更新都会和 React 事件内部的更新一样批量处理: + +```js +// React 18 中 timeout、promise、 +// 本地事件处理函数或者其他任何事件的更新都会批量处理。 + +function handleClick() { + setCount(c => c + 1); + setFlag(f => !f); + // React 只会在结束的时候重新渲染一次(这就是批量处理!) +} + +setTimeout(() => { + setCount(c => c + 1); + setFlag(f => !f); + // React 只会在结束的时候重新渲染一次(这就是批量处理!) +}, 1000); +``` + +这是一个破坏性变更,但是我们期望这个变更可以产生更少的渲染工作,从而提高应用的性能表现。为了有选择性地使用自动化处理,你可以使用 `flushSync` 包裹: + +```js +import { flushSync } from 'react-dom'; + +function handleClick() { + flushSync(() => { + setCounter(c => c + 1); + }); + // React 现在已经更新了 DOM + flushSync(() => { + setFlag(f => !f); + }); + // React 现在已经更新了 DOM +} +``` + +更多信息请查看 [深入探索自动批处理](https://github.com/reactwg/react-18/discussions/21)。 + +## 新 API {#new-apis-for-libraries} + +在 React 18 工作组,我们和第三方库的维护者合作,创建需要支持 styles 和外部存储中的特定用例的并发渲染的新 API。为了支持 React 18,一些第三方库可能需要切换到下面的 API 之一: + +* `useSyncExternalStore` 是一个新增 Hook,它允许外部存储通过对 store 的强制更新保持同步从而支持并发读取。这个新 API 推荐用于任何和 React 的外部状态集成的库。了解更多信息请查看 [useSyncExternalStore 概览](https://github.com/reactwg/react-18/discussions/70) 和 [useSyncExternalStore API 细节](https://github.com/reactwg/react-18/discussions/86)。 +* `useInsertionEffect` 是一个新增 Hook,它可以让 CSS-in-JS 库解决渲染中注入样式的性能问题。我们希望只有在你已经构建了一个 CSS-in-JS 库的情况下才使用它。这个 Hook 会在 DOM 变化之后,layout Effect 读取新的布局之前运行。这解决了 React 17 及其以下就已经存在但是在 React 18 更重要的问题,因为在并发渲染期间 React 会阻止浏览器,给了它一个重新计算布局的机会。了解更多信息,查看 [``),都需要在 DOM 中进行精确的定位,因为样式优先级规则。构建一个允许在组件内部进行组合的样式表功能是困难的,所以用户通常要么将所有的样式远离可能依赖它们的组件加载,要么使用一个封装了这种复杂性的样式库。 + +在 React 19 中,我们正在解决这个复杂性,并提供更深入的集成到客户端的并发渲染和服务器的流式渲染,内置支持样式表。如果你告诉 React 你的样式表的 `precedence`,它将管理样式表在 DOM 中的插入顺序,并确保在显示依赖于这些样式规则的内容之前加载样式表(如果是外部的)。 + +```js{4,5,17} +function ComponentOne() { + return ( + + + +
+ {...} +
+
+ ) +} + +function ComponentTwo() { + return ( +
+

{...}

+ <-- will be inserted between foo & bar +
+ ) +} +``` + +在服务器端渲染时,React 会在 `` 中包含样式表,确保浏览器在加载完样式表之前不会进行绘制。如果在已经开始流式传输后才发现样式表,React 会确保在揭示依赖于该样式表的 Suspense 边界的内容之前,将样式表插入到客户端的 `` 中。 + +在客户端渲染时,React 会等待新渲染的样式表加载完成后再提交渲染。如果你在应用程序的多个地方渲染此组件,React 会只在文档中包含一次样式表: + +```js{5} +function App() { + return <> + + ... + // won't lead to a duplicate stylesheet link in the DOM + +} +``` + +对于习惯于手动加载样式表的用户来说,这是一个机会,可以将这些样式表放在依赖它们的组件旁边,从而更好地进行本地推理,并确保只加载你实际依赖的样式表。 + +样式库和与打包器的样式集成也可以采用这种新的功能,所以即使你不直接渲染你自己的样式表,你也可以从你的工具升级到使用这个特性中受益。 + +有关更多详细信息,请阅读 [``](/reference/react-dom/components/link) 和 [` +``` + +::: + +对于独立系统来说,命令式地控制用户界面的效果也不错,但是当处于更加复杂的系统中时,这会造成管理的困难程度指数级地增长。如同示例一样,想象一下,当你想更新这样一个包含着不同表单的页面时,你想要添加一个新 UI 元素或一个新的交互,为了保证不会因此产生新的 bug(例如忘记去显示或隐藏一些东西),你必须十分小心地去检查所有已经写好的代码。 + +React 正是为了解决这样的问题而诞生的。 + +在 React 中,你不必直接去操作 UI —— 你不必直接启用、关闭、显示或隐藏组件。相反,你只需要 **声明你想要显示的内容,** React 就会通过计算得出该如何去更新 UI。想象一下,当你上了一辆出租车并且告诉司机你想去哪,而不是事无巨细地告诉他该如何走。将你带到目的地是司机的工作,他们甚至可能知道一些你没有想过并且不知道的捷径! + + + +## 声明式地考虑 UI {#thinking-about-ui-declaratively} + +你已经从上面的例子看到如何去实现一个表单了,为了更好地理解如何在 React 中思考,接下来你将会学到如何用 React 重新实现这个 UI: + +1. **定位**你的组件中不同的视图状态 +2. **确定**是什么触发了这些 state 的改变 +3. **表示**内存中的 state(需要使用 `useState`) +4. **删除**任何不必要的 state 变量 +5. **连接**事件处理函数去设置 state + +### 步骤 1:定位组件中不同的视图状态 {#step-1-identify-your-components-different-visual-states} + +在计算机科学中,你或许听过可处于多种“状态”之一的 [“状态机”](https://en.wikipedia.org/wiki/Finite-state_machine)。如果你有与设计师一起工作,那么你可能已经见过不同“视图状态”的模拟图。正因为 React 站在设计与计算机科学的交点上,因此这两种思想都是灵感的来源。 + +首先,你需要去可视化 UI 界面中用户可能看到的所有不同的“状态”: + +* **无数据**:表单有一个不可用状态的“提交”按钮。 +* **输入中**:表单有一个可用状态的“提交”按钮。 +* **提交中**:表单完全处于不可用状态,加载动画出现。 +* **成功时**:显示“成功”的消息而非表单。 +* **错误时**:与输入状态类似,但会多错误的消息。 + +像一个设计师一样,你会想要在你添加逻辑之前去“模拟”不同的状态或创建“模拟状态”。例如下面的例子,这是一个对表单可视部分的模拟。这个模拟被一个 `status` 的属性控制,并且这个属性的默认值为 `empty`。 + +::: code-group + +```js [App.js] +export default function Form({ + status = 'empty' +}) { + if (status === 'success') { + return

That's right!

+ } + return ( + <> +

City quiz

+

+ In which city is there a billboard that turns air into drinkable water? +

+
+ ` 这样的子元素,你应该 [使用 `defaultValue` 提供初始值](#providing-an-initial-value-for-a-text-area)。 +- 如果一个文本框接收字符串类型的 `value` 属性,那么它将被视为 [受控组件](#controlling-a-text-area-with-a-state-variable)。 +- 一个文本框不能同时既是受控组件又是非受控组件。 +- 一个文本框在其生命周期内无法在受控和非受控之间切换。 +- 每个受控文本框都需要一个 `onChange` 事件处理程序,以同步更新其后面的新值。 + +--- + +## 用法 {#usage} + +### 展示一个文本框 {#displaying-a-text-area} + +使用 `` 将不受支持。 + + + +--- + +### 提交表单时读取文本框的值 {#reading-the-text-area-value-when-submitting-a-form} + +在文本框周围添加一个包含 [` + + +
+

That's right!

+ + +``` + +::: + +Manipulating the UI imperatively works well enough for isolated examples, but it gets exponentially more difficult to manage in more complex systems. Imagine updating a page full of different forms like this one. Adding a new UI element or a new interaction would require carefully checking all existing code to make sure you haven't introduced a bug (for example, forgetting to show or hide something). + +React was built to solve this problem. + +In React, you don't directly manipulate the UI--meaning you don't enable, disable, show, or hide components directly. Instead, you **declare what you want to show,** and React figures out how to update the UI. Think of getting into a taxi and telling the driver where you want to go instead of telling them exactly where to turn. It's the driver's job to get you there, and they might even know some shortcuts you haven't considered! + + + +## Thinking about UI declaratively {#thinking-about-ui-declaratively} + +You've seen how to implement a form imperatively above. To better understand how to think in React, you'll walk through reimplementing this UI in React below: + +1. **Identify** your component's different visual states +2. **Determine** what triggers those state changes +3. **Represent** the state in memory using `useState` +4. **Remove** any non-essential state variables +5. **Connect** the event handlers to set the state + +### Step 1: Identify your component's different visual states {#step-1-identify-your-components-different-visual-states} + +In computer science, you may hear about a ["state machine"](https://en.wikipedia.org/wiki/Finite-state_machine) being in one of several “states”. If you work with a designer, you may have seen mockups for different "visual states". React stands at the intersection of design and computer science, so both of these ideas are sources of inspiration. + +First, you need to visualize all the different "states" of the UI the user might see: + +* **Empty**: Form has a disabled "Submit" button. +* **Typing**: Form has an enabled "Submit" button. +* **Submitting**: Form is completely disabled. Spinner is shown. +* **Success**: "Thank you" message is shown instead of a form. +* **Error**: Same as Typing state, but with an extra error message. + +Just like a designer, you'll want to "mock up" or create "mocks" for the different states before you add logic. For example, here is a mock for just the visual part of the form. This mock is controlled by a prop called `status` with a default value of `'empty'`: + +::: code-group + +```js [App.js] +export default function Form({ + status = 'empty' +}) { + if (status === 'success') { + return

That's right!

+ } + return ( + <> +

City quiz

+

+ In which city is there a billboard that turns air into drinkable water? +

+
+ ` is not allowed. [Use `defaultValue` for initial content.](#providing-an-initial-value-for-a-text-area) +- If a text area receives a string `value` prop, it will be [treated as controlled.](#controlling-a-text-area-with-a-state-variable) +- A text area can't be both controlled and uncontrolled at the same time. +- A text area cannot switch between being controlled or uncontrolled over its lifetime. +- Every controlled text area needs an `onChange` event handler that synchronously updates its backing value. + +--- + +## Usage {#usage} + +### Displaying a text area {#displaying-a-text-area} + +Render `` is not supported. + + + +--- + +### Reading the text area value when submitting a form {#reading-the-text-area-value-when-submitting-a-form} + +Add a [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form) around your textarea with a [`