react-router-component 相关问题


反应问题,当我将标头组件添加到我的主页组件时,没有任何内容加载

从“react”导入React; 从 '@chakra-ui/react' 导入 { ChakraProvider, CSSReset }; 从 'react-router-dom' 导入 { BrowserRouter as Router, Route, Routes }; 从 './nav' 导入导航; 导入首页


React Router v6.4+ 数据 API:重试加载程序而不显示错误

使用react-router 6.21.1和新的数据api,我的路由设置如下: 常量路由 = [ { 元素: , 错误元素:, 孩子们...


使用react-router-v6和zustand进行身份验证

应用程序路线: 函数 AppRoutes(): JSX.Element { 返回 ( } /> }> ...


React Router:第一次访问 ParentNotificationsPage 组件时不显示数据,仅在返回后才显示

我在 React 应用程序中遇到了 React Router 的问题,其中 ParentNotificationsPage 组件在第一次访问时不显示数据。仅当我导航回


React 组件的样式与其他组件的样式冲突

我有一个像这样的应用程序组件: 常量应用程序 = () => { 返回 ( 我有一个像这样的应用程序组件: const App = () => { return ( <Router> <Route exact path='/' component={Landing} /> <Route path='/login' component={Login} /> </Router> ) } 每个组件都有自己的目录和样式表。我的文件夹结构是这样的: src | | Landing| | | | Landing.js | Landing.module.css | | Login| | | | Login.js | Login.module.css | app.js index.js 我的问题是Login和Landing组件的样式表相互冲突,并且Landing页面看起来不太好。例如,登录的背景颜色适用于登陆页面,但我不希望这样。 我只在每个组件中导入 CSS 文件,如下所示: import styles from './Landing.module.css' 这是我如何使用样式变量的示例: return ( <div className={styles.navBar}> <Link to="/"> <img className={styles.logo} src="https://image.flaticon.com/icons/png/512/2039/2039175.png" /> </Link> {loggedIn && <div> <button onClick={logout}>log out</button> <Link className={styles.navItem} to="/users">get users</Link> </div> } {!loggedIn && <div> <Link className={styles.navItem} to="/login">log in</Link> <Link className={styles.navItem, styles.btn} to="/signup">signup</Link> </div> } </div> ) 即使它很旧,我也会回答谁在后面:发生这种情况的原因是你的CSS选择器很可能具有相同的特异性,因此是外观的顺序决定了应用哪种样式。 文件夹结构中的 Login 位于 Landing 之后,因此您的捆绑程序将使 Login 的样式出现在捆绑的 CSS 中的最后,然后它将覆盖 Landing 的样式。 这个问题有很多解决方案: 您可以增加您想要赢得的选择器的特异性(例如,通过在 CSS 文件中重复两次该类) 您可以降低想要丢失的选择器的特异性(例如使用 :where()) 如果您同意支持哪些浏览器(例如@layer),现在您可以使用级联层 等等...


React Router 为动态路由渲染错误组件的问题

我遇到了 React Router 的问题,使用动态参数导航到特定 URL 会渲染错误的组件。具体来说,当导航到 http://localhost:3001/Create/4 时,...


this.props.history.push() 似乎不再在 React Router v4 中工作,有什么替代方案吗?

我是 React 新手,我看到的大多数有关使用 React Router 进行重定向的教程似乎都在使用上述代码片段。我想要实现的是将用户重定向到主页...


React store.getState 不是一个函数

这是我的代码: 商店.js 从 'redux' 导入 {createStore, applyMiddleware, compose}; 从“不可变”导入{fromJS}; 从“react-router-redux”导入{routerMiddleware}; 导入createSagaMidd...


当React Router中的路由命中时,如何有条件地渲染两个组件或更改两个出口?

我有一个 React 应用程序,我在其中使用 React Router。在我的布局组件中,我有这样的结构: 从“反应”导入反应; 从 './components/Header/Header' 导入标头; 导入 Foo...


Typescript、React、强类型 useHistory

我将 useHistory (react-router-dom) 变量作为参数发送到employee.service,其中我使用带有状态和路径名的“history.push”方法。不幸的是我不能...


NG8001:“app-welcome”不是已知元素:

我的 Angular 应用程序遇到问题,收到错误 8001。我不知道如何处理它。谁能帮我这个?谢谢你! 应用程序组件.html {{标题}}&l... 我的 Angular 应用程序遇到问题,收到错误 8001。我不知道如何处理它。谁能帮我这个?谢谢! app.component.html <h1>{{ title }}</h1> <p>Congratulations! Your app is running. 🎉</p> <app-welcome></app-welcome> app.component.ts import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [CommonModule, RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = 'XYZCARS'; } welcome.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-welcome', templateUrl: './welcome.component.html', styleUrl: './welcome.component.css' }) export class WelcomeComponent { car = 'toyota'; } 我的项目最初没有 app.module.ts 文件。我自己添加了它并根据网上找到的一些信息进行了配置,但问题仍然存在并且仍未解决。谁能帮我解决这个问题吗? app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { WelcomeComponent } from './welcome/welcome.component'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, WelcomeComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } 如果您正在 Angular 17 中创建项目->使用这些命令 ng app --no-standalone 然后你就得到了 app.module.ts 文件。


有没有办法清除react中的react历史记录?

我有一个针对移动用户的 Web 应用程序,但由于我们的客户不需要移动应用程序,因此它是使用 React 开发的。我已经使用 React Router 实现了应用内路由。我用


链接点击时的反应模式调用

使用react-modal,我需要通过锚标记或react-router-dom链接单击超链接时显示模式。 示例:单击注册超链接,注册表模式应打开。


在loader中使用URL参数时出现错误

我在我的 React 项目中使用 React-Router。我有一个如下所示的移动页面: 从“反应”导入反应; 从 'axios' 导入 axios 导出异步函数加载器({ params }) { ...


如何处理默认路径

我在我的网站上使用 React Router,遇到了以下问题。我的主要应用程序组件定义如下: 导入'./App.css' 从 './Navbar' 导入 { Navbar } 进口 { 出口 } f...


什么在 Next.js next/navigation 中的react-router-dom 中替换 useLocation() ?

最近,我从 React 迁移到 Next.js [email protected]。在我的网站中,我在使用 useNavigate() 推送时使用了状态,并使用 useLocation() 从另一个页面获取值。我怎样才能做同样的事...


React、React Router、Joy UI:如何禁用导航离开和返回后重新出现的小吃栏?

我有一个虚拟的工作板 Web 应用程序,它使用 React 和 Joy UI 作为前端和 UI。我使用 Joy UI 的 Snackbar 组件在用户执行某些操作后临时弹出一条消息(


React-router:更改 URL 并清除历史记录

我有以下场景: 用户打开激活链接;用户完成激活过程后,系统会将其移动到另一个页面。 我不想保留激活状态...


检查我在React Js中的路线

如果我在某条路线中导航,我想做一个三叶草,然后如果我在我想要的路线中,则有条件地执行一个函数,但我找不到一种方法来做到这一点。我想使用 React router dom 但如果...


Expo 路由器问题:React Native 中基于文件的路由出现不匹配的路由错误

我在 React Native 中遇到了 Expo Router 的令人沮丧的问题。尽管设置了基于文件的路由,但我仍然收到“不匹配的路由”错误。我的目标是引导用户


错误:链接需要在项目的 Expo 配置(app.config.js 或 app.json)中进行构建时设置 `scheme`

我使用react-native expo bare-workflow创建了该项目 npx create-expo-app --template bare-minimum 创建项目后,我尝试将expo-router安装到项目中,一切都完成了


React Router - 如何确定是否按下了后退按钮?

我有这些场景 设置页面 -> 结果页面 -> 详细信息页面 用户选择设置,单击下一步,获取结果,然后单击查看更多详细信息。 详情页 -> 结果页 用户去...


React中react-router-dom最新版本如何实现延迟加载

我想使用Typescript在React中实现延迟加载。我收到打字稿错误。 常量应用程序 = () => { 返回 ( 我想使用 Typescript 在 React 中实现延迟加载。我收到打字稿错误。 const App = () => { return ( <RouterProvider router={createBrowserRouter( createRoutesFromElements( <Route> <Route path="/" element={<Outlet/>}> <Route index element={<Home />} /> <Route path="contact" element={<Contact />} /> <Route path="about" element={<About />} /> <Route path="*" element={<Navigate to="/" replace />} /> </Route> </Route> ) )} /> ) }; export default App; 下面的代码不起作用 <Route> <Route path="/" element={<Outlet/>}> <Route index lazy={() => import("./Home")} /> <Route path="contact" lazy={() => import("./Contact")} /> <Route path="about" lazy={() => import("./About")} /> <Route path="*" element={<Navigate to="/" replace />} /> </Route> </Route> const Home= lazy(() => import("./screens/home")); const About= lazy(() => import("./screens/about")); <Route> <Route path="/" element={<Outlet/>}> <Route index element={<Suspense fallback={<div>Loading...</div>}> <Home/> </Suspense> /> } /> <Route path="about" element={<Suspense fallback={<div>Loading...</div>}> <About/> </Suspense> /> } /> <Route path="*" element={<Navigate to="/" replace />} /> </Route> </Route>


react-hook-form useForm 每次在 Nextjs 页面路由上执行

嗨,我是 Nextjs(v14) 的新手。我想使用react-hook-form 实现多页面表单。 然而,似乎每次都会执行useForm,并且defaultValues是在页面路由中设置的(点击 嗨,我是 Nextjs(v14) 的新手。我想使用react-hook-form 实现多页面表单。 不过,好像每次都会执行useForm,并且在页面路由时设置defaultValues(点击<Link to=XX>)。 如何跨多个页面保存表单数据? 请帮助我。 这是我的代码。 _app.tsx return ( <div> <FormProvider> <Component {...pageProps} /> </FormProvider> </div> ); FormProvider.tsx export const FormProvider = ({ children, }: { children: React.ReactNode; }) => { const defaultValues: MyForm = { name: '', description: '' }; const form = useForm({ defaultValues, resolver: zodResolver(MyFormSchema), }); const onSubmit = () => console.log("something to do"); return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}>{children}</form> </Form> ); }; 您正在寻找的是跨多个页面维护的某种全局状态。对于这个例子,我将使用 React 的上下文 API,如果这不适合您的用例,您可以找到一些其他状态管理库。 首先,您需要创建一个全局上下文,并在表单提供程序中包含一个全局状态 // FormProvider.tsx import { createContext, useContext, useState } from 'react'; const FormContext = createContext(); // Exported to be used in other components export const useFormContext = () => useContext(FormContext); export const FormProvider = ({ children }) => { const [formData, setFormData] = useState({}); return ( <FormContext.Provider value={{ formData, setFormData }}> {children} </FormContext.Provider> ); }; 现在您需要用 FormProvider 包装您的应用程序 // You are already doing this part //_app.tsx return ( <div> <FormProvider> <Component {...pageProps} /> </FormProvider> </div> ) 现在你可以像这样使用它了。请记住,您将更新表单的全局状态,该状态将在您的所有页面上发生变化。 // In your form component import { useForm } from 'react-hook-form'; import { useFormContext } from '../path/to/formContext'; const MyFormComponent = () => { const { formData, setFormData } = useFormContext(); const { register, handleSubmit } = useForm({ defaultValues: formData, resolver: zodResolver(MyFormSchema), }); const onSubmit = (data) => { setFormData(data); // Handle form submission }; return ( <form onSubmit={handleSubmit(onSubmit)}> {/* Form fields */} </form> ); }; 您可以从其他页面访问数据的示例 // In another page or component import { useFormContext } from '../path/to/formContext'; const AnotherPage = () => { const { formData } = useFormContext(); // Use formData as needed };


将 props 传递给 nextjs 中的页面组件

我正在使用 nextjs 的 withlayout 函数为某些页面添加侧边栏。 导出类型 PageWithLayout = NextPage & { withLayout?:(页面:ReactElement)=> 我正在使用 nextjs 的 withlayout 函数为某些页面添加侧边栏。 export type PageWithLayout<P = {}, IP = P> = NextPage<P, IP> & { withLayout?: (page: ReactElement) => ReactNode; }; 这是我的使用方法: export const Interactions: PageWithLayout = () => { const [ getInteractions, { data: interactionData, fetchMore, variables, loading: isInteractionsLoading, error: isInteractionsError, }, ] = useGetInteractionsLazyQuery({ notifyOnNetworkStatusChange: true, fetchPolicy: "network-only", ssr: false, }); return ( <> <Box height={"100vh"}> </Box> </> ); }; Interactions.withLayout = (page: ReactElement) => { // how do I pass isInteractionsLoading as a prop to this component return <Layout>{page}</Layout>; }; export default Interactions; 我想要实现的是将 isInteractionsLoaded 和 isInteractionsError 作为属性传递给我的布局组件,以便我可以渲染这些状态。有没有一种方法可以实现此目的,而无需将布局组件移动到页面组件内? 创建一个包装组件的 React Context 提供程序可能是您使用的解决方案,如果您不想使用任何其他包或不想使用 redux 等更强大的工具,则可以使用。 但是在这里使用有点尴尬,具体取决于包含交互的组件树是什么样子。否则可以根据您的需要使用 _app 入口点。 示例上下文和用法 import React from 'react'; export const InteractionContext = React.createContext({ isInteractionsLoading: false, isInteractionsError: null, }); // parent component or _app if necessary const ProviderComponent = () => { return ( <InteractionContext.Provider value={{ isInteractionsLoading, isInteractionsError }}> <Interactions /> </InteractionContext.Provider> ); }; const Layout = ({ children }) => { const { isInteractionsLoading, isInteractionsError } = useContext(InteractionContext); // Now you can use isInteractionsLoading and isInteractionsError here // ... return <div>{children}</div>; };


React Router v6 使用参数导航

目前,我在实现React Router v6(使用6.3.0)时遇到问题 假设我有如下所示的路由 const ParticipantRoutes = () => ( 目前,我在实现React Router v6(使用6.3.0)时遇到问题 假设我有如下所示的路由 const ParticipantRoutes = () => ( <ErrorBoundaryRoutes> <Route index element={<Participant />} /> <Route path="new" element={<ParticipantUpdate />} /> <Route path=":id"> <Route index element={<ParticipantDetail />} /> <Route path=":id"> <Route path="edit-invoice" element={<InvoiceUpdate />}/> </Route> <Route path="invoice" element={<ParticipantInvoiceUpdate />} /> <Route path="edit" element={<ParticipantUpdate />} /> <Route path="delete" element={<ParticipantDeleteDialog />} /> </Route> </ErrorBoundaryRoutes> ); 还有另一条路线,比如 const InvoiceRoutes = () => ( <ErrorBoundaryRoutes> <Route index element={<Invoice />} /> <Route path=":id"> <Route index element={<InvoiceDetail />} /> <Route path="delete" element={<InvoiceDeleteDialog />} /> <Route path="payment" element={<InvoicePaidDialog />} /> </Route> </ErrorBoundaryRoutes> ); 当我访问 URL 上定义的 ParticipantInvoiceUpdate 时,问题就出现了,比如 .../participant/*some-guid-participant*/*some-guid-participant-invoice*/edit-invoice 此页面具有向某些服务提交一些数据的行为,当接受服务器的响应时,我使用导航功能导航回 ParticipantDetail 元素。 navigate('/participant/${*some-guid-participant*}'); 但它不起作用,我尝试了一些东西,但似乎它只能导航到没有给出任何参数的元素。类似的东西 navigate('/participant'); 或 navigate('/invoice); 我也尝试过使用 generatePath 功能并将其与导航结合起来,但仍然没有成功 navigate(generatePath('/participant/:id',{id: participantId}), {replace:true}); 请帮助了解我是否遗漏了什么或误解了这个概念。 根据您的代码,路线:.../participant/*some-guid-participant*/*some-guid-participant-invoice*/edit-invoice 指组件 InvoiceUpdate 而不是 ParticipantInvoiceUpdate 此外,使用字符串格式时不要忘记将 ' 更改为 ` : navigate(`/participant/${some-guid-participant}`);


Quasar Vue Router 解析名为route的href

我正在尝试使用 vue router 构建 href 链接 我在routes.js中有以下内容 常量路由 = [ { 小路: ”/”, 组件:() => import("layouts/MainLayout.vue")...


vue-router useRouter 在构建库组件时不起作用

我正在构建一个 Vue3 npm 组件库,希望我可以使用 vue-router 的 useRouter 访问当前路由器,并且它将由导入我的任何 vue 应用程序自动提供


如何使用 2 个条件角度选择器

我有一个带有选择器的多输入组件,如下所示: 我有一个带有选择器的多输入组件,如下所示: <app-input type="currency" formControlName="currency"></app-input> <app-input type="date" formControlName="dateOfBirth"></app-input> 因此,从该组件中,我有一个像这样的选择器: @Component({ selector: 'app-input[type=currency]', }) @Component({ selector: 'app-input[type=date]', }) 现在,我想添加多个 currency 组件。一种用于默认货币成分,第二种用于具有动态货币符号的货币。 所以,我想通过选项让它变得不同。当选择器有选项时,显示带动态符号的货币,否则或默认,显示不带符号的默认货币。 我一直在尝试使用下面的这个选择器,但它不起作用。 对于默认货币: @Component({ selector: 'app-input:not([options])[type=currency]', }) 对于动态符号货币: @Component({ selector: 'app-input[options][type=currency]', }) 提前谢谢您 您可以像这样添加数据属性来区分选择器 无符号: @Component({ selector: 'app-input[type=currency]', }) 带有符号: @Component({ selector: 'app-input[type=currency][data-symbols]', }) html with symbols: <app-input type="currency" formControlName="currency" data-symbols></app-input> without symbols: <app-input type="currency" formControlName="currency"></app-input>


TrustPilot Id 在硬重新加载时不显示

我有这个角度组件,似乎使 TrustPilot 小部件在硬刷新后消失,任何人都可以解释为什么吗? 从 '@angular/core' 导入 { Component, Input, OnInit }; 宣告全球...


Angular16 中的 Router parseUrl() 与 navigate()

我正在使用 authGuard 进行身份验证。我想知道这两个之间的区别 // 重定向到登录页面 return router.navigate(['/login']); return router.parseUrl('/login'); 在...


声明文件中的类型继承

我正在声明其他元素类型应该满足的“父”COMPONENT 类型。如果我在普通的 .ts 或 .tsx 文件中使用下面的代码,它可以正常工作(也就是说,它会显示我无法使用...


将 YAML 文件注入构造函数

我有这个 YAML 文件 src/main/resources/foo.yml: 酒吧: - 你好 - 世界 巴兹: - 洛雷姆 - ipsum 这个组件: @成分 公共类我的组件{ 公共我的组件(地图 我有这个 YAML 文件 src/main/resources/foo.yml: bar: - hello - world baz: - lorem - ipsum 这个组件: @Component public class MyComponent { public MyComponent(Map<String, List<String>> foo) { // foo.get("bar") } } 使用 Spring Boot 2.7,是否可以将配置按原样(自己的文件,无前缀,无类)注入到构造函数中? 你可以这样做 @Configuration public class MyConfiguration { @Bean public Map<String, Object> foo(@Value("classpath:foo.yaml") Resource yaml) { Yaml yaml = new Yaml(); return yaml.load(yaml.getInputStream()); } } @Component public class MyComponent { public MyComponent(@Qualifier("foo") Map<String, Object> foo) { ... } }


onMounted 当没有要关联的活动组件实例时调用

Symfony/VueJS 组件 // 导入 从“../hooks/getUser”导入 getUser; 从 'vue-router' 导入 { useRoute } // 增值服务 常量路由 = useRoute() 常量 { 用户 } = getUser(1) const 路线我...


Nuxt 3 项目无法找到 PWA 图标

开发工具错误 我目前正在尝试在我的 nuxt 3 项目中实现 PWA 功能,但我不断遇到这个问题:[Vue Router warn]: No match found for location with path "/icon_512x512...


将哈希从 Mule 3 转换到 Mule 4 时遇到问题

有人知道 Mule 4 相当于下面的 Mule 3 代码吗? 有人知道 Mule 4 相当于下面的 Mule 3 代码吗? <expression-component doc:name="TECH_Heroku_PartKey"><![CDATA[ payload=com.google.common.hash.Hashing.sha1().hashBytes(payload.getBytes("UTF-8")); ]]></expression-component> hashWith()可以在DataWeave 2中使用不同算法生成哈希,包括SHA1。 您需要注意,结果可能会根据有效负载的不同而有所不同。我猜测在 Mule 3 中你正在将 Java 字符串转换为字节。在 Mule 4 中,hashWith() 函数需要一个二进制文件。你会测试一下。 或者,您可以将相同的代码放入 Java 方法中并使用 Java 模块调用它。


我无法打印onChange的值

从“react”导入React; 从“react-input-mask”导入InputMask; 从“./inputMask.module.scss”导入样式; 从“反应...


Vue 3如何获取$children的信息

这是我在 Tabs 组件中使用 VUE 2 的旧代码: 创建(){ this.tabs = this.$children; } 标签: .... 这是我在 Tabs 组件中使用 VUE 2 的旧代码: created() { this.tabs = this.$children; } 标签: <Tabs> <Tab title="tab title"> .... </Tab> <Tab title="tab title"> .... </Tab> </Tabs> VUE 3: 如何使用组合 API 获取有关 Tabs 组件中子项的一些信息?获取长度,迭代它们,并创建选项卡标题,...等?有任何想法吗? (使用组合API) 这是我现在的 Vue 3 组件。我使用 Provide 来获取子 Tab 组件中的信息。 <template> <div class="tabs"> <div class="tabs-header"> <div v-for="(tab, index) in tabs" :key="index" @click="selectTab(index)" :class="{'tab-selected': index === selectedIndex}" class="tab" > {{ tab.props.title }} </div> </div> <slot></slot> </div> </template> <script lang="ts"> import {defineComponent, reactive, provide, onMounted, onBeforeMount, toRefs, VNode} from "vue"; interface TabProps { title: string; } export default defineComponent({ name: "Tabs", setup(_, {slots}) { const state = reactive({ selectedIndex: 0, tabs: [] as VNode<TabProps>[], count: 0 }); provide("TabsProvider", state); const selectTab = (i: number) => { state.selectedIndex = i; }; onBeforeMount(() => { if (slots.default) { state.tabs = slots.default().filter((child) => child.type.name === "Tab"); } }); onMounted(() => { selectTab(0); }); return {...toRefs(state), selectTab}; } }); </script> 选项卡组件: <script lang="ts"> export default defineComponent({ name: "Tab", setup() { const index = ref(0); const isActive = ref(false); const tabs = inject("TabsProvider"); watch( () => tabs.selectedIndex, () => { isActive.value = index.value === tabs.selectedIndex; } ); onBeforeMount(() => { index.value = tabs.count; tabs.count++; isActive.value = index.value === tabs.selectedIndex; }); return {index, isActive}; } }); </script> <template> <div class="tab" v-show="isActive"> <slot></slot> </div> </template> 哦伙计们,我解决了: this.$slots.default().filter(child => child.type.name === 'Tab') 对于想要完整代码的人: 标签.vue <template> <div> <div class="tabs"> <ul> <li v-for="tab in tabs" :class="{ 'is-active': tab.isActive }"> <a :href="tab.href" @click="selectTab(tab)">{{ tab.name }}</a> </li> </ul> </div> <div class="tabs-details"> <slot></slot> </div> </div> </template> <script> export default { name: "Tabs", data() { return {tabs: [] }; }, created() { }, methods: { selectTab(selectedTab) { this.tabs.forEach(tab => { tab.isActive = (tab.name == selectedTab.name); }); } } } </script> <style scoped> </style> 标签.vue <template> <div v-show="isActive"><slot></slot></div> </template> <script> export default { name: "Tab", props: { name: { required: true }, selected: { default: false} }, data() { return { isActive: false }; }, computed: { href() { return '#' + this.name.toLowerCase().replace(/ /g, '-'); } }, mounted() { this.isActive = this.selected; }, created() { this.$parent.tabs.push(this); }, } </script> <style scoped> </style> 应用程序.js <template> <Tabs> <Tab :selected="true" :name="'a'"> aa </Tab> <Tab :name="'b'"> bb </Tab> <Tab :name="'c'"> cc </Tab> </Tabs> <template/> 我扫描子元素的解决方案(在对 vue 代码进行大量筛选之后)是这样的。 export function findChildren(parent, matcher) { const found = []; const root = parent.$.subTree; walk(root, child => { if (!matcher || matcher.test(child.$options.name)) { found.push(child); } }); return found; } function walk(vnode, cb) { if (!vnode) return; if (vnode.component) { const proxy = vnode.component.proxy; if (proxy) cb(vnode.component.proxy); walk(vnode.component.subTree, cb); } else if (vnode.shapeFlag & 16) { const vnodes = vnode.children; for (let i = 0; i < vnodes.length; i++) { walk(vnodes[i], cb); } } } 这将返回子组件。我对此的用途是我有一些通用的对话框处理代码,用于搜索子表单元素组件以咨询其有效性状态。 const found = findChildren(this, /^(OSelect|OInput|OInputitems)$/); const invalid = found.filter(input => !input.checkHtml5Validity()); 如果你复制粘贴与我相同的代码 然后只需向“选项卡”组件添加一个创建的方法,该方法将自身添加到其父级的选项卡数组中 created() { this.$parent.tabs.push(this); }, 使用脚本设置语法,您可以使用useSlots:https://vuejs.org/api/sfc-script-setup.html#useslots-useattrs <script setup> import { useSlots, ref, computed } from 'vue'; const props = defineProps({ perPage: { type: Number, required: true, }, }); const slots = useSlots(); const amountToShow = ref(props.perPage); const totalChildrenCount = computed(() => slots.default()[0].children.length); const childrenToShow = computed(() => slots.default()[0].children.slice(0, amountToShow.value)); </script> <template> <component :is="child" v-for="(child, index) in childrenToShow" :key="`show-more-${child.key}-${index}`" ></component> </template> 我对 Ingrid Oberbüchler 的组件做了一个小改进,因为它不支持热重载/动态选项卡。 在 Tab.vue 中: onBeforeMount(() => { // ... }) onBeforeUnmount(() => { tabs.count-- }) 在 Tabs.vue 中: const selectTab = // ... // ... watch( () => state.count, () => { if (slots.default) { state.tabs = slots.default().filter((child) => child.type.name === "Tab") } } ) 我也遇到了同样的问题,在做了很多研究并问自己为什么他们删除了$children之后,我发现他们创建了一个更好、更优雅的替代方案。 这是关于动态组件的。 (<component: is =" currentTabComponent "> </component>). 我在这里找到的信息: https://v3.vuejs.org/guide/component-basics.html#dynamic-components 希望这对你有用,向大家问好!! 我发现这个更新的 Vue3 教程使用 Vue 插槽构建可重用的选项卡组件对于与我相关的解释非常有帮助。 它使用 ref、provide 和ject 来替换我遇到同样问题的this.tabs = this.$children;。 我一直在遵循我最初发现的构建选项卡组件(Vue2)的教程的早期版本创建您自己的可重用 Vue 选项卡组件。 根据 Vue 文档,假设您在 Tabs 组件下有一个默认插槽,您可以直接在模板中访问该插槽的子级,如下所示: // Tabs component <template> <div v-if="$slots && $slots.default && $slots.default()[0]" class="tabs-container"> <button v-for="(tab, index) in getTabs($slots.default()[0].children)" :key="index" :class="{ active: modelValue === index }" @click="$emit('update:model-value', index)" > <span> {{ tab.props.title }} </span> </button> </div> <slot></slot> </template> <script setup> defineProps({ modelValue: Number }) defineEmits(['update:model-value']) const getTabs = tabs => { if (Array.isArray(tabs)) { return tabs.filter(tab => tab.type.name === 'Tab') } else { return [] } </script> <style> ... </style> 并且 Tab 组件可能类似于: // Tab component <template> <div v-show="active"> <slot></slot> </div> </template> <script> export default { name: 'Tab' } </script> <script setup> defineProps({ active: Boolean, title: String }) </script> 实现应类似于以下内容(考虑一组对象,每个部分一个,带有 title 和 component): ... <tabs v-model="active"> <tab v-for="(section, index) in sections" :key="index" :title="section.title" :active="index === active" > <component :is="section.component" ></component> </app-tab> </app-tabs> ... <script setup> import { ref } from 'vue' const active = ref(0) </script> 另一种方法是使用 useSlots,如 Vue 文档(上面的链接)中所述。 在 3.x 中,$children 属性已被删除并且不再受支持。相反,如果您需要访问子组件实例,他们建议使用 $refs。作为数组 https://v3-migration.vuejs.org/writing-changes/children.html#_2-x-syntax 在 3.x 版本中,$children 已被删除且不再受支持。使用 ref 访问子实例。 <script setup> import { ref, onMounted } from 'vue' import ChildComponent from './ChildComponent .vue' const child = ref(null) onMounted(() => { console.log(child.value) // log an instance of <Child /> }) </script> <template> <ChildComponent ref="child" /> </template> 详细信息:https://vuejs.org/guide/essentials/template-refs.html#template-refs 基于@Urkle的回答: /** * walks a node down * @param vnode * @param cb */ export function walk(vnode, cb) { if (!vnode) return; if (vnode.component) { const proxy = vnode.component.proxy; if (proxy) cb(vnode.component.proxy); walk(vnode.component.subTree, cb); } else if (vnode.shapeFlag & 16) { const vnodes = vnode.children; for (let i = 0; i < vnodes.length; i++) { walk(vnodes[i], cb); } } } 除了已接受的答案之外: 而不是 this.$root.$children.forEach(component => {}) 写 walk(this.$root, component => {}) 这就是我让它为我工作的方式。


Vue 3 简单的包罗万象的后备路由在服务器上不起作用

我使用 Vue router 4 创建了一个新的 Vue 3 应用程序。 当我通过 访问链接时,它会打开页面,但是当我直接打开链接时,它会显示未找到错误。 { 不是芙...


无法在react-三纤维中导入dat.gui

对于使用react- Three-Fiber制作的项目,我导入了以下库: 从 '三' 导入 * 作为三; 从“react”导入 React, { Suspense, useState }; 导入 { 画布,useLoader }


为什么我导入 React 时服务器返回 MIME 类型为“text/html”?

这是我的js: 从'./node_modules/react'导入React; 从'./node_modules/react-dom'导入ReactDOM; 让 thePage = React.createElement( '主要的', 无效的, '哈哈' ); ReactDOM.render(thePage,


尽管已安装,但找不到模块“@tanstack/react-table”

我正在开发一个 TypeScript React 项目,我正在尝试从 columns.tsx 文件中的 @tanstack/react-table 导入 ColumnDef。 从“@tanstack/react-table”导入{ColumnDef}; 出口...


创建新的 React 应用程序时遇到麻烦

当我尝试创建一个新的 React 应用程序时,我收到以下错误消息, 安装软件包。这可能需要几分钟。安装中 React、react-dom 和带有 cra-temp 的 React-scripts...


react-testing-library:无法关闭 MUI Select 的下拉菜单

我有一个 SelectExample.js 从“react”导入 React, { useState }; 从“@mui/material”导入{InputLabel、MenuItem、FormControl、Select、Typography };> 导出默认fu...


在React版本18中使用react-facebook-login

我希望将react-facebook-login库与React版本18一起使用,但我无法安装该包。 npm 在控制台上抛出错误? 该库是否支持 Reac 18 版本...


如何在 EAS 构建中使用 React Native Reanimated?

我按照react-native-reanimated文档的安装说明创建了两次相同的应用程序https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/ge...


React-select:虚拟化选项列表

在最新版本的react-select(3.1.0)中虚拟化选项列表的预期方式是什么? 有react-virtualized-select,但不再支持。谢谢。


升级到 React 18 后 React App 未渲染

`我的 React 应用程序运行良好,但升级到 React 18、mui v5 和 redux v5 后,它没有渲染任何内容。 在终端中,我得到: webpack 编译成功 但在 chrome 控制台中...


元素未显示在 React Native 上

电流输出: 预期输出: 当前代码实施: 从“反应”导入反应 从 'react-native-svg-charts' 导入 { LineChart, XAxis, YAxis } 从 'react-native' 导入 { View, Text }


create-react 应用程序的替代品是什么

我有一个基于 Create React App 构建的 React 项目,我正在探索替代构建工具。有哪些推荐的方法或工具可以从 Create React App 迁移出来?有什么经历或


© www.soinside.com 2019 - 2024. All rights reserved.